天天看点

关于super

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