This is an experimental technology, part of the ECMAScript 6 (Harmony) proposal.
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.
The extends
keyword is used in a class declarations or class expressions to create a class with a child of another class.
Syntax
class ChildClass extends ParentClass { ... }
Description
The extends
keyword can be used to subclass custom classes as well as built-in objects.
Examples
The first example creates a class called Square
from a class called Polygon
.
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; } set area(value) { this.area = value; } }
This example extends the built-in Date
object.
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(); } }
Demo
The above examples are extracted from this live demo. (source)
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 6 (ECMA-262) The definition of 'extends' in that specification. |
Release Candidate | Initial definition. |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 42.0 | Available in the Nightly channel only (since March 2015) | ? | ? | ? |
Array subclassing | 43.0 | Not supported | ? | ? | ? |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | 42.0 | 42.0 | Available in the Nightly channel only (since March 2015) | ? | ? | ? |
Array subclassing | 43.0 | ? | Not supported | ? | ? | ? |