super關(guān)鍵字

super關(guān)鍵字用于訪問(wèn)和調(diào)用一個(gè)父對(duì)象上的函數(shù)。
在構(gòu)造函數(shù)中使用時(shí),super必須放在this之前,否則,會(huì)報(bào)錯(cuò)。

1.在類中使用super

class Polygon {
    constructor(height, width) {
        this.name = 'Polygon';
        this.height = height;
        this.width = width;
    }
    sayName() {
        console.log('Hi, I am a ', this.name + '.');
    }
}

class Square extends Polygon {
    constructor(length) {
        //this.height;  //this不允許使用在super前
        super(length, length);
        this.name = 'Square';
    }

    get area() {
        return this.height * this.width;
    }

    set area(value) {
        //this.area = value;
        console.log(value);
    }
}

var res = new Square(2);
console.log(res,res.area); //Square { name: 'Square', height: 2, width: 2 } 4
res.sayName(); //Hi, I am a  Square.

2. 調(diào)用父類的靜態(tài)方法

class Human {
    constructor() {}
    static ping() {
        return 'ping';
    }
}

class Computer extends Human {
    constructor() {}
    static pingpong() {
        return super.ping() + ' pong';
    }
}
console.log(Computer.pingpong());  //ping pong

3.不能使用delete操作符刪除super上的屬性
class Base {
constructor() {}
foo() {}
}
class Derived extends Base {
constructor() {}
delete() {
 delete super.foo;
}
}

new Derived().delete(); 
// ReferenceError: invalid delete involving 'super'.

4.當(dāng)使用 Object.defineProperty 定義一個(gè)屬性為不可寫時(shí),super將不能重寫這個(gè)屬性的值。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 第3章 基本概念 3.1 語(yǔ)法 3.2 關(guān)鍵字和保留字 3.3 變量 3.4 數(shù)據(jù)類型 5種簡(jiǎn)單數(shù)據(jù)類型:Unde...
    RickCole閱讀 5,527評(píng)論 0 21
  • 1.ios高性能編程 (1).內(nèi)層 最小的內(nèi)層平均值和峰值(2).耗電量 高效的算法和數(shù)據(jù)結(jié)構(gòu)(3).初始化時(shí)...
    歐辰_OSR閱讀 30,252評(píng)論 8 265
  • 1 無(wú)論ARC還是MRC,編譯器會(huì)給我們生成setter與getter方法的聲明與實(shí)現(xiàn)。 2 屬性或成員變量可以是...
    cmhfx1閱讀 1,513評(píng)論 0 0
  • 在我看來(lái)正常的事,很多人表示不理解。我喜歡的東西身邊的人也不怎么喜歡。我所表達(dá)的看法,好像有點(diǎn)弱智。我所說(shuō)的話好像...
    iamzzz閱讀 672評(píng)論 0 0
  • 究竟我想要的是什么生活,追求的是什么?金錢、權(quán)力、親情、友情、愛(ài)情? 一個(gè)人的路,秘密太多,沒(méi)有目標(biāo),沒(méi)有夢(mèng)想,那...
    安之密語(yǔ)閱讀 260評(píng)論 0 0

友情鏈接更多精彩內(nèi)容