What is a constructor in Javascript ?

If you have been working on or learning Object Oriented JavaScript, you must have come across the word “constructor” a number of times.

A constructor is basically a function that is used to set the properties and methods of an Object.

Generally you may use “this” keyword within the Constructor function a lot and the “new” keyword to call the constructor. Let’s look at an example :

//Constructor function
/**
* The 'this' keyword in the constructor would refer to 
* the individual object instances that would be created using the 'New' Keyword
**/
function Person(name, age, gender)
{
   this.name = name;
   this.age = age;
   this.gender = gender;
}

//Creation of an instance of the Person Object

var person = new Person('John', 27, 'Male');

/* Usage */
person.name; // returns 'John'
person.age; // returns 27

How to find the constructor of an Object in JavaScript ?

Given an Object, you can find out its Constructor by using the ‘constructor’ keyword. You need to use “Object.constructor” to identify the Object’s constructor. Please note that the “Object” here would most probably be an Instance of the Object that we must have created using the “new” keyword.

E.g :

/* To find the Constructor of the instance of the Object Person
** that we created in the previous example, try the following: */

person.constructor;

/*Returns 
function Person(name, age, gender)
{
  ...
}
*/

If you notice, using the constructor object returns the complete constructor function, i.e the Person function as per our example.

In the book JavaScript The Complete Reference 3rd Edition the Author Thomas Powell explains in detail the uses of a constructor function and other object oriented JavaScript techniques. A must buy book for everybody interested in JavaScript.
Using constructors are very helpful especially if you want your code to stay organized and you want to have that extra flexibility to use features of object oriented JavaScript.

Hope you now understand what a constructor is. Let us know your thoughts on constructor.