--- title: extends slug: Web/JavaScript/Reference/Classes/extends tags: - Classes - ECMAScript 2015 - JavaScript translation_of: Web/JavaScript/Reference/Classes/extends ---
extends关键字用于类声明或者类表达式中,以创建一个类,该类是另一个类的子类。
class ChildClass extends ParentClass { ... }
extends关键字用来创建一个普通类或者内建对象的子类。
继承的.prototype必须是一个{{jsxref("Object")}} 或者 {{jsxref("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与内置对象这个示例继承了内置的{{jsxref("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可以像扩展普通类一样扩展{{jsxref("null")}},但是新对象的原型将不会继承 {{jsxref("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 | 
|---|---|---|
| {{SpecName('ES2015', '#sec-class-definitions', 'extends')}} | {{Spec2('ES2015')}} | Initial definition. | 
| {{SpecName('ESDraft', '#sec-class-definitions', 'extends')}} | {{Spec2('ESDraft')}} | 
{{Compat("javascript.classes.extends")}}