-
子类的constructor()中必须有super(),目的是调用父类的构造函数。
class Father { constructor(x) { this.x = x; } } class Son extends Father { constructor() { super(); } } -
子类中 ,当super作为对象时,指向父类,可在子类中调用父类的方法。
class Father { constructor() { this.x = 1; } say() { console.log(2); } } class Son extends Father { constructor() { super(); } sayTo() { super.say(); } } var father = new Father(); var son = new Son(); son.sayTo(); //2 -
子类中,super作为对象时,如果更改super的属性,那么此时super并不指向父类,而是等同于this。
class Father { constructor() { this.x = 1; } } class Son extends Father { constructor() { super(); } change() { super.x = 2; } say() { console.log(this.x); } } var father = new Father(); var son = new Son(); console.log(son.x); //1 son.change(); son.say(); //2 console.log(father.x); //1