梗概

  • 子类调用依次使用所有父类的构造函数来构造自己
    • 即使是父类的构造函数,其中的this是指向子类的
  1. super()只能在constructor(){}中使用

实例:

let father =class{
  constructor(父类形参1,父类形参2){
    this.父类动态属性1 ="I'm in the father. "+父类形参1;
    this.子父类动态同名异值属性 ="I'm in the father. "+父类形参2;
  }
  父类固定属性1 = "I'm in the father. "
}
let son = class extends father{
  constructor(子类形参1,子类形参2){
    super(子类形参1,子类形参2);
    this.子父类动态同名异值属性 ="I'm in the son. "+子类形参2
  }
}
let test = new son("实参1!","实参2!");
console.log("test.父类固定属性1:          "+test.父类固定属性1);//输出 I'm in the father. 
console.log("test.父类动态属性1:          "+test.父类动态属性1);//输出 I'm in the father. 实参1!
console.log("test.子父类动态同名异值属性:  "+test.子父类动态同名异值属性)//输出 I'm in the son. 实参2!
  1. 该例中传参过程中将实参1!实参2!传到constructor(子类形参1,子类形参2)
  2. 再传到super(子类形参1,子类形参2)
  3. 再传到constructor(父类形参1,父类形参2)
  4. 再传到this.父类动态属性1 ="I'm in the father. "+父类形参1;this.子父类动态同名异值属性 ="I'm in the father. "+父类形参2;
    1. ==注意!== 此时这个this指向改变为子类

原理

  • super相当于父类构造函数.call(this,子类形参1,子类形参2)