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 :

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 :

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.