Constructors are functions, through which objects are created. The objects have same methods and properties as constructors. JavaScript has built-in constructors like Object, Array, Function …etc. Users can create their own constructors using function keyword and using capital letter for the name of the constructor. Any number of objects can be created from a constructor.

Basic example of a constructor in JavaScript

//constructor example
function Vehicle(variables…) {
    //Properties and methods here
}

To create object from the constructor, the keyword new is used. If there are any parameters to be passed to the constructor, it is passed at the time of declaration of the object. Constructors do not return anything.

Another small example of a constructor

var vehicle1 = new Vehicle(“Mercedes”);

To check if an object is created with the “new” operator, instanceof operator is used. To check the type of instance created, === operator can be used.

Examples of instanceof and === operators

document.write(vehicle1 instanceof Vehicle); //Returns true if object is created.

document.write(vehicle1.constructor === Vehicle) //Returns true

Different properties and methods can be added to the constructors, as shown below. The constructor takes a parameter input (name) assigns to it’s property “name”. getName() method returns the “name” property of the constructor. “this” is the object which gets created with “new” operator. It is instance of the constructor type.

Example of a constructor's properties and methods

//constructor example
function Vehicle(name) {
    this.name = name;
    this.getName = function() {
       return(this.name);
   }
}

Advantages of using constructors

Constructors are easy to use for single page applications.

Disadvantages of using constructors

Each time an object is created with keyword new, a new copy of the methods of the constructor is created. This is not an efficient usage of memory.

It does not use inheritance, hence we cannot do a proper OO programming.

 

›› go to examples ››