ES6 筆記 Class和繼承

定義class

class Point {
  //optional, 如果沒寫,相當(dāng)于寫了空的構(gòu)造函數(shù)
  constructor(x, y) {
    this.x = x; //實例屬性
    this.y = y; 
  }

  //定義在構(gòu)造方法的prototype上
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }

  //get 方法
  get propName() { ... }

  //set方法 
  set propName(arg) { ... }

  //方法名由變量生成
  [functionThatReturnsPropertyName()] (args) { ... }

  //定義在構(gòu)造方法上
  static draw(circle, canvas) {
      // Canvas drawing code
  };
  
  //定義在構(gòu)造方法上
  static get circlesMade() {
      return !this._count ? 0 : this._count;
  };
}

通過extend來繼承父類的屬性和方法

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

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

Mix

mix允許繼承多個類的屬性(實例屬性和prototype屬性)

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

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

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