The confusion between a “function” and a “constructor” is always there. They may seem very similar from outside, but its the implementation that defines the difference. Actually its not even the function definition which is confusing, but its the concept and dynamism of the language itself.
First important thing to remember is everything in Javascript is an Object.
So anything that is Object can be functional. Now there are two ways we can create objects in javascript.
The basic and most used is the object literal with curly braces as
var myObj={
a:12,
b:"another string",
c:function(){}
};
Now if we want to access any thing of this object, the calls will go as below
myObj.a;
myObj.c();
That was quite straight forward for we are accessing an “object itself”.
Now lets see how we can create objects in another way.
var AnObject=function(){
this.a='A String value';
this.b=12345;
this.c=function(){};
this.d='Another String';
};
The above code is kind of a Class, that means it is not a class by any formal definition, but it is kind of a thing which makes objects. If one tries to access anything from it directly as
AnObject.a;
AnObject.c();
It will simply not work!! Why?! For its not an Object yet. To make an object out of it, we have to use “new” and then call it with a “()” like
var anO=new AnObject();
//now call the properties and methods as below
anO.a;
anO.c();
Thats simply because when we call this kind of object, or create objects in this kind with a “new” and a “()”, its called constructor.
varv anO=new AnObject();
Now this function call with a “new” is known as a constructor.
Apart from this difference there is a huge difference in terms of using “prototype” object of the constructor. The “prototype” itself is a huge topic, so its not explained here. The important thing here is to remember that any object which is created with a constructor has a “prototype” property but the objects, which are created with any other methods do not possess the “prototype” object.