ES6中。类与继承的方法,以及与ES5中的方法的对比

时间:2023-02-11 18:38:08

// 在ES5中,通常使用构造函数方法去实现类与继承

         // 创建父类
function Father(name, age){
this.name = name;
this.age = age;
}
Father.prototype.show = function(){
console.log(this.name);
console.log(this.age);
} const obj = new Father('李大师', 30);
obj.show(); // 输出 李大师 30 // 创建子类,然后让子类继承父类
function Child(name,age,sex){
//继承第一句:让子类实例化的对象具备父类的所有属性
Father.apply(this,arguments);
this.sex = sex;
}
//继承第二句:让子类实例化对象具备父类的所有原型方法
Child.prototype = Object.create(Father.prototype); //继承第三句:找回丢失的构造函数
Child.prototype.constructor = Child; Child.prototype.run = function(){
console.log(this.sex)
} const son = new Child('123', 10, 'boy');
son.show(); // 输出 123 10
son.run(); // 输出boy

// ES6中,类的实现和继承非常方便

class SuperClass{
//实例化类时默认会执行构造函数
constructor(name,age){
//初始化对象的语句
this.name=name;
this.age=age;
} //原型方法
show(){
console.log(this.name);
console.log(this.age);
}
} const sup = new SuperClass('super', 20);
sup.show(); // 输出 super 20 class SonClass extends SuperClass{
constructor(name, age, sex){
super(name,age); // name 和 age属性可以继承父类
this.sex = sex; // sex 属性 子类自己定义
} run(){
console.log(this.sex);
}
} const sonclass = new SonClass('abc', 15, 'girl');
sonclass.show(); // 输出 abc 15
sonclass.run(); // 输出 girl