super不僅僅是一個關鍵字,還可以作為函數和對象。
函數:在子類繼承父類中,super作為函數調用,隻能寫在子類的構造函數(constructor)裡面,super代表的是父類的構造函數,
難點了解
但是執行過時supre()代表的是子類,super()裡面的this指向子類的執行個體對象this。
class A {
constructor() {
console.log(new.target.name);
}
class B extends A {
super();//這裡的super相當于A類的constructor構造函數,會執行A的constructor,但是此時的this指
//向的是B,是以列印出B
//換一種方法了解是:在執行super時,A把constructor方法給了B,此時B有了A的功能,但是執
//行的是B的内容,也就是es5的A.prototype.constructor.call(this)。
new A() // A
new B() // B
——————————————————————————————————————————————————————
對象:
這裡重點了解下對象,概念相對抽象
super作為對象使用時,分為在普通方法中使用和在靜态方法中使用
在普通方法找中使用:super指向父類的原型,即A.prototype,可以通路到原型上的方法和屬性
邏輯抽象一:
ES6 規定,在子類普通方法中通過super調用父類的方法時,方法内部的this指向目前的子類執行個體。
this.x = 1;
print() {
console.log(this.x);
super();
this.x = 2;
m() {
super.print();
let b = new B();
b.m() // 2
super.print()雖然調用的是A.prototype.print(),但是A.prototype.print()内部的this指向子類B的執行個體
———————————————————————————————————————————————————————
super作為對象,用在靜态方法之中,這時super将指向父類,而不是父類的原型對象。
class Parent {
static myMethod(msg) {
console.log('static', msg);
myMethod(msg) {
console.log('instance', msg);
class Child extends Parent {
super.myMethod(msg);
Child.myMethod(1); // static 1
var child = new Child();
child.myMethod(2); // instance 2