继承

Sep 28, 2022

首先,继承的是 属性 和 原型方法

ES6 继承

ES6:https://es6.ruanyifeng.com/#docs/class-extends

Class 可以通过extends关键字实现继承,让子类继承父类的属性和方法

子类如果写 constructor()就必须要写 super(),且要写在最前面,否则报错,只有super()方法才能让子类实例继承父类。

👊ps: ES6 规定,子类必须在constructor()方法中调用super(),否则就会报错。这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,添加子类自己的实例属性和方法。如果不调用super()方法,子类就得不到自己的this对象。

class Parent {
  constructor(x,y) {
    this.x = x
        this.y = y
        ...
  }
    toString() {
    ...
  }
}
class Son extends Parent {
  constructor(x, y, color) {
    super(x, y); // 调用父类的constructor(x, y)
    this.color = color;
  }
  toString() {
    return this.color + ' ' + super.toString(); // 调用父类的toString()
  }
}
ES5 继承

js 中有很多中继承的方式,不过每一种继承方式都有优缺点,重点掌握 ES5 继承,别的继承方式基本都是 ES5 继承的语法糖

先创造子类实例,通过Parent.call(this, arg1, arg2...)将父类的属性方法添加到this上,继承了父类的属性

再通过 Son.prototype = Object.create( Father.prototype )将父类的原型继承过来

最后可以通过Son.prototype.constructor = Son 将子类的原型指到子类身上

function Father(name) {
    this.name = name;
}
Father.prototype.get = function () {
    return "优秀的";
};
// 继承的是 属性 和 原型方法
function Son(name) {
    Father.call(this, name);
}
// Son.prototype = new Father() // 相互影响 会存在一个 {name:undefined}
// Object.create 创造出一个空对象
// 让当前对象的__proto__ 指向传入的对象
Son.prototype = Object.create(Father.prototype);
Son.prototype.constructor = Son;
const father = new Father("Father")
const son = new Son("程序员");
console.log(son);
console.log(son.get() + son.name); // 优秀的程序员
Back