JavaScript Class Constructor Method

Definition and usage

constructor() A method is a special method used to create and initialize objects created in a class.

When initializing a class,constructor() Methods are automatically called, and they must use the exact name "constructor", actually, if you do not have a constructor, JavaScript will add an invisible empty constructor.

Note:A class cannot use multiple constructor() methods. This will throw SyntaxError.

You can use super() methods to call the parent class's constructor (see more examples below).

Instance

Example 1

Create a Car class and then create an object named "mycar" based on this Car class:

class Car {
  constructor(brand) {  // Constructor
    this.carname = brand;
  }
}
mycar = new Car("Ford");

Try It Yourself

Example 2

To create class inheritance, use Extends keyword.

Classes created by class inheritance will inherit all methods from another class.

Create a class named "Model" that will inherit the methods of the "Car" class:

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present() {
    return 'I have a ' + this.carname;
  }
}
class Model extends Car {
  constructor(brand, mod) {
    super(brand);
    this.model = mod;
  }
  show() {
    return this.present() + ', it is a ' + this.model;
  }
}
mycar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = mycar.show();

Try It Yourself

super() method to refer to the parent class.

By calling super() methods, we will call the parent class's constructor and can access the properties and methods of the parent class.

Syntax

constructor(parameters)

Technical Details

JavaScript Version: ECMAScript 2015 (ES6)

Browser Support

Method Chrome IE Firefox Safari Opera
constructor() 49.0 13.0 45.0 9.0 36.0

Related Pages

JavaScript Tutorial:JavaScript Class

JavaScript Tutorial:JavaScript ES6 (EcmaScript 2015)

JavaScript Reference Manual:Extends Keyword

JavaScript Reference Manual:Super Keyword