Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

constructor

Our volunteers haven't translated this article into Tiếng Việt yet. Join us and help get the job done!

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.

If you don't specify a constructor method, a default constructor is used.

Examples

Using the constructor method

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;
  } 
}

Default constructors

If you don't specify a constructor method, a default constructor is used. For base classes, the default constructor is:

constructor() {}

For derived classes, the default constructor is:

constructor(...args) {
  super(...args);
}

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Constructor Method' in that specification.
Standard Initial definition.
ECMAScript 2017 Draft (ECMA-262)
The definition of 'Constructor Method' in that specification.
Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 42.0 45 (45) ? ? ?
Default constructors ? 45 (45) ? ? ?
Feature Android Android Webview Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support No support 42.0 45.0 (45) ? ? ? 42.0
Default constructors ? ? 45.0 (45) ? ? ? ?

See also

Document Tags and Contributors

 Contributors to this page: fscholz, rwaldron, jpmedley, llue
 Last updated by: fscholz,