What is a constructor in JavaScript?
A Constructor is a function that creates an instance of a class, which is typically called an objects. In other words you can say “A constructor is a function which is used to create an object.”
In JavaScript a constructor gets called, when you declear an object using new
keyword.
For example:
In the above example the Person
is an object constructor function. The purpose of a constructor is to create an object and set values if there are any object properties present.
In the above example, to create an object from a constructor function, we use the new
keyword. It’s a neat way to create an object because you do not need to explicitly state what to return as the constructor function.
Let’s say there is an object, Person, which have to properties fname
and age
. If you want to intialize the two instaces with the different name, with the help of same constructor function.
You can use same properties(fname, age) either you can add the property in the individual instances.
In JavaScript, here is what happens when a constructor is invoked:
- A new empty object is created.
this
keyword starts referring to that newly created object and hence it becomes the current instance object.- The newly created object is then returned as the constructor’s returned value.