Skip to content

ES5 和 ES6 继承 ​

2023-03-02 15:17:13

ES6 ​

es6 中通过 class 关键字创建类,通过 extend 来实现继承效果,让子类继承父类的属性和方法

ES5 ​

原型链继承 ​

原型链继承的原理很简单,直接让子类的原型对象指向父类的实例,当子类的实例找不到对应的属性和方法时,就会往它的原型对象,也就是父类实例上找,从而实现对父类的属性和方法的继承

ts
function Person() {
  this.name = 'Back_kk'
}
Person.prototype.getName = function () {
  return this.name
}
function Student() {}
Student.prototype = new Person()
// 根据原型链的规则,顺便绑定一下constructor, 这一步不影响继承, 只是在用到constructor时会需要
// 原型的实例等于自身
Student.prototype.constructor = Student

const student = new Student()
console.log(student.name) // Back_kk
console.log(student.getName()) // Back_kk

缺点:当修改一个子类的来自父类的引用类型会影响所有的子类实例

构造函数式继承 ​

构造函数继承,即在子类的构造函数中执行父类的构造函数,并为其绑定子类的this,让父类的构造函数把成员属性和方法都挂到子类的this上去,这样既能避免实例之间共享一个原型实例,又能向父类构造方法传参。

ts
function Person(name) {
    this.name = name
}
Person.prototype.getName = function() {
    return this.name;
}
function Student() {
    Person.apply(this, arguments);
}

const student = new Student('Back_kk');
console.log(student.name); // Back_kk

组合式继承 ​

寄生式组合继承 ​

Released under the MIT License.