Fork me on GitHub

ES5的继承与ES6的继承的区别——FEI面试官养成系列

ES5的继承

ES5的继承是先创建子类的实例, 然后再创建父类的方法添加到this上.

通过原型和构造函数机制实现的.

// ES5的继承
// 原型链方式: 子类的原型指向父类的实例
// 缺点: 1. 因为原型链继承共享实例属性,属于引用类型传值, 修改某个实例的属性会影响其他的实例 2. 不能实时向父类的构造函数中传值, 很不方便
function Parent() {
    this.values = [1];
}
function Child(){

}
Child.prototype = new Parent();
const child1 = new Child();
console.log(child1.values); // [ 1 ]
child1.values.push(2);
const child2 = new Child();
console.log(child2.values); // [ 1, 2 ]

ES6的继承

ES6的继承是先创建父类的实例对象this(必须先调用super方法), 再调用子类的构造函数修改this.

通过关键字class定义类, extends关键字实现继承. 子类必须在constructor方法中调用super方法否则创建实例报错. 因为子类没有this对象, 而是使用父类的this, 然后对其进行加工

super关键字指代父类的this, 在子类的构造函数中, 必须先调用super, 然后才能使用this

// ES6的继承
// 在子类的构造器中先调用super(), 创建出父类实例, 然后再去修改子类中的this去完善子类
class Parent {
    constructor(a, b) {
        this.a = a;
        this.b = b;
    }
}

class Child extends Parent {
    constructor(a, b, c) {
        super(a, b);
        this.c = c;
    }
}

const child = new Child(1, 2, 3);
console.log(child); // { a: 1, b: 2, c: 3 }
posted @ 2021-11-23 18:40  思考的大腿  阅读(223)  评论(0编辑  收藏  举报