class繼承

class ColorPoint extends Point {
  constructor(x, y, color) {
    super(x, y); // 調(diào)用父類的constructor(x, y)
    this.color = color;
  }

  toString() {
    return this.color + ' ' + super.toString(); // 調(diào)用父類的toString()
  }
}

子類必須在constructor方法中調(diào)用super方法,否則新建實(shí)例時(shí)會(huì)報(bào)錯(cuò)

class Point { /* ... */ }

class ColorPoint extends Point {
  constructor() {
  }
}

let cp = new ColorPoint(); // ReferenceError

ES5 的繼承,實(shí)質(zhì)是先創(chuàng)造子類的實(shí)例對(duì)象this,然后再將父類的方法添加到this上面(Parent.apply(this))。ES6 的繼承機(jī)制完全不同,實(shí)質(zhì)是先創(chuàng)造父類的實(shí)例對(duì)象this(所以必須先調(diào)用super方法),然后再用子類的構(gòu)造函數(shù)修改this。

父類的靜態(tài)方法,也會(huì)被子類繼承

class A {
  static hello() {
    console.log('hello world');
  }
}

class B extends A {
}

B.hello()  // hello world

class A {}

class B extends A {
  constructor() {
    super();
  }
}

super內(nèi)部的this指向的是B

class A {}

class B extends A {
  m() {
    super(); // 報(bào)錯(cuò)
  }
}


?著作權(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),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 1.class可以通過extends關(guān)鍵字實(shí)現(xiàn)繼承,比es5的通過修改原型鏈實(shí)現(xiàn)繼承,要清晰和方便。 子類必須在c...
    ningluo閱讀 286評(píng)論 0 1
  • 文章來源阮一峰ES6入門,這里做要點(diǎn)掌握大綱。class——構(gòu)造函數(shù)的語法糖ES5的繼承:修改原型鏈先創(chuàng)造子類的實(shí)...
    宋樂怡閱讀 1,663評(píng)論 0 0
  • 這是16年5月份編輯的一份比較雜亂適合自己觀看的學(xué)習(xí)記錄文檔,今天18年5月份再次想寫文章,發(fā)現(xiàn)簡書還為我保存起的...
    Jenaral閱讀 3,143評(píng)論 2 9
  • 1.構(gòu)造函數(shù),原型,實(shí)例之間的關(guān)系 每個(gè)構(gòu)造函數(shù)都有一個(gè)原型對(duì)象(prototype屬性),原型對(duì)象都包含一個(gè)指向...
    秦小婕閱讀 903評(píng)論 0 0
  • 簡介 Class可以通過extends關(guān)鍵字實(shí)現(xiàn)繼承。 上面代碼定義了一個(gè)ColorPoint類,該類通過exte...
    oWSQo閱讀 757評(píng)論 0 1

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