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.
Summary
The constructor
method is a special method for creating and initializing an object created with a class
.
Syntax
constructor([arguments]) { ... }
Description
There can only be one special method with the name "constructor" in a class. A SyntaxError
will be thrown, if the class contains more than one occurrence of a constructor
method.
A constructor can use the super
keyword to call the constructor of a parent class.
Examples
This code snippet is taken from the classes sample (live demo).
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; } }
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 6 (ECMA-262) The definition of 'Constructor Method' 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 February 2015) | ? | ? | ? |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | ? | 42.0 | Available in the Nightly channel only (since February 2015) | ? | ? | ? |
Firefox-specific notes
- Default constructors are not implemented yet (bug 1105463)