extends

extends关键字用于类声明或者类表达式中,以创建一个类,该类是另一个类的子类。

语法

class ChildClass extends ParentClass { ... }

描述

extends关键字用来创建一个普通类或者内建对象的子类。

继承的.prototype必须是一个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

可以像扩展普通类一样扩展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)
extends
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
extends
Draft  

浏览器兼容

Update compatibility data on GitHub
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
extends Chrome 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 13 Firefox Full support 45 IE No support No Opera Full support 36 Safari Full support 9 WebView Android 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".
Chrome Android 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".
Firefox Android Full support 45 Opera Android ? Safari iOS Full support 9 Samsung Internet Android Full support Yes nodejs 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.

扩展阅读