{{jsSidebar("Classes")}} {{Harmony}}
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 {{jsxref("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 |
---|---|---|
{{SpecName('ES6', '#sec-static-semantics-constructormethod', 'Constructor Method')}} | {{Spec2('ES6')}} | Initial definition. |
Browser compatibility
{{CompatibilityTable}}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | {{CompatChrome(42.0)}} | {{CompatNightly}} | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatUnknown}} |
Feature | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|---|
Basic support | {{CompatNo}} | {{CompatChrome(42.0)}} | {{CompatNightly}} | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatChrome(42.0)}} |
Firefox-specific notes
- Default constructors are not implemented yet ({{bug(1105463)}})