ES6对象的super关键字

super是es6新出的关键字,它既可以当作函数使用,也可以当作对象使用,两种使用方法不尽相同

1.super用作函数使用的时候,代表父类的构造函数,es6规定在子类中使用this之前必须先执行一次super函数,super相当于Father.prototype.constructor.call(this)

class Father{
    constructor(){
        this.a = 1;
    }
}
class Son extends Father{
    constructor(){
        super();
    }
}

2.super用作对象的时候,在普通方法中指向父类的原型对象,在静态方法中指向父类

  子类中使用super无法访问Father的实例属性a,可以访问原型对象上的p

class Father {
    constructor() {
        this.a = 1;
    }
    p() {
     console.log(thia.a); console.log(
'hello'); } } class Son extends Father { constructor() { super();
     this.a = 2; super.p();
//'2 hello' Father.prototype.p()方法内部的this指向的是子类实例 super.a;//undefined } }
  • 静态方法中指向的是父类,而非父类的构造函数
  • static method中super指向父类Parent,相当于访问Parent.myMethod
  • 普通  method中super指向父类Parent的prototype,相当于访问Parent.prototype.myMethod
class Parent {
    static myMethod(msg) {
        console.log('static', msg);
    }
    myMethod(msg) {
        console.log('instance', msg);
    }
}
class Child extends Parent {
    static myMethod(msg) {
        super.myMethod(msg);  //super指向父类因此访问的是static myMethod
    }
    myMethod(msg) {
        super.myMethod(msg);  //super指向的是父类的构造函数,访问的是Parent.prototype.myMethod
    }
}
Child.myMethod(222);//static 222

let child = new Child;
child.myMethod(111);//instance 111  
原文地址:https://www.cnblogs.com/yinping/p/11234019.html