By definition, a constructor function is a normal Javascript function. Nothing more, nothing less. What makes a function a constructor is how it is used. When a function is used in such a way that it can create an object, by calling it with Javascript's new operator, then it becomes a constructor function.
This means all and any function you have in Javascript can be used as a constructor function.
var Person = function () {
console.log("I am a function");
}
We can call this function normally:
Person(); //prints to the console "I am a function"
console.log(typeof Person) //prints to the console ‘function’
So let’s now use this function as a constructor and create an object:
Now let us confirm that bond is indeed an object:
console.log(typeof bond) //this prints "Object"
Now that is all about Constructor functions. It is as simple as that: A function that is the same as your normal Javascript function but can be used to create objects.
But you would notice that the object created above is empty (without properties) and maybe of little or no use. Compared to the example given in my
previous post, which had properties.
So how do you actually make an object with some already set properties at creation? Before we go ahead and look at this, its worth mentioning a characteristics of functions in Javascript (apart from this fact that they can be used to create objects).
Functions are first class citizens in Javascript and also Functions can have properties just as objects! Yes just like you add properties to an object, you can do same to a Javascript function.