ES6 super 关键字

262 阅读1分钟

super 是es6新出的关键字,可以当作函数使用,也可以当作对象使用

一、super 当做函数使用

super 当做函数使用时,super 代表其父类的构造函数 constructor,super()相当于Father.prototype.constructor.call(this)

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

二、super 用作对象使用

2-1 普通方法中使用

super在普通方法中指向父类的原型对象

// super 作为对象在普通方法中使用
class Father {
    constructor() {
        this.a = 1;
    }
    //p函数是挂载到Father原型上的
    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    super无法访问Father的实例属性a,只可以访问其原型对象上的p
    }
}

2-2 静态方法中使用

super在静态方法中指向父类

// super 作为对象在静态方法中使用
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