extends 關鍵字被使用於類別(class)宣告類別(class)表達式中來建立擴展的子類別 。

語法

class ChildClass extends ParentClass { ... }

解釋

extends 關鍵字可用於建立一個自訂類別或內建類別的子類別。

其繼承之原型 .prototype 必須是 Object 或 null

範例

使用 extends

第一個範例是根據 Polygon類別建立一個名為 Square 的子類別。此範例提取自線上示例

class Square extends Polygon {
  constructor(length) {
    // Here, it calls the parent class' constructor with lengths
    // provided for the Polygon's width and height
    super(length, length);
    // Note: In derived classes, super() must be called before you
    // can use 'this'. Leaving this out will cause a reference error.
    this.name = 'Square';
  }

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

使用 extends 於內建類別

這個範例擴展了內建的 Date 類別。此範例提取自線上範例

class myDate extends Date {
  constructor() {
    super();
  }

  getFormattedDate() {
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
  }
}

擴展 null

像擴展普通類別一樣擴展 null,但新對象的原型不會繼承 Object.prototype

class nullExtends extends null {
  constructor() {}
}

Object.getPrototypeOf(nullExtends); // Function.prototype
Object.getPrototypeOf(nullExtends.prototype) // null

new nullExtends(); //ReferenceError: this is not defined

標準

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'extends' in that specification.
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
The definition of 'extends' in that specification.
Draft  

瀏覽器相容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Basic supportChrome Full support 49
Notes
Full support 49
Notes
Notes From Chrome 42 to 48 strict mode is required. Non-strict mode support can be enabled using the flag "Enable Experimental JavaScript".
Edge Full support 13Firefox Full support 45IE No support NoOpera Full support 36Safari Full support 9WebView Android ? Chrome Android Full support YesEdge Mobile Full support 13Firefox Android Full support 45Opera Android ? Safari iOS Full support 9Samsung Internet Android Full support Yesnodejs Full support 6.0.0
Full support 6.0.0
Full support 4.0.0
Disabled
Disabled From version 4.0.0: this feature is behind the --use_strict runtime flag.
Full support 5.0.0
Disabled
Disabled From version 5.0.0: this feature is behind the --harmony runtime flag.

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.

參見

文件標籤與貢獻者

此頁面的貢獻者: Aries0d0f
最近更新: Aries0d0f,