ES6對象的super關鍵字

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

在這裏插入圖片描述

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章