Constructors in JavaScripts! Sounds odd. Right?

But yes Constructors in JavaScripts are widely used by developers now days. And you too should consider it, as it may help you make your code neat.

Enough Gyan! Lets code:

function Programmer(id,name)  
{  
this.id = id;  
this.name = name;  
this.describe = function(){
console.log(this.name + “ hates javascript!”);}  
}  
var m = new Programmer(“Bill”,420);  
console.log(m); //{id: 420, name: “Bill”, describe: function()}   

(Note Capital P in Programmer, this is the notion used for constructors,first capital alphabet.)

Above code creates an object and assign appropriate values to it using self defined constructor.

Role of new keyword-

  1. Creates an empty object which is referenced by “this” keyword which inherits the prototype of the function.
  2. Returns object referred by this if no object is returned explicitly.

We can imagine the role of new keyword as:

function Programmer(id,name)  
{  
//creates an empty object viz this  
//var this = {};  
this.id = id;  
this.name = name;  
this.describe = function(){console.log(this.name + “ hates javascript!”);}  
//insert all properties/methods of prototype object into this  
//return this;  
}  

That simple!

Another thing which you will want to consider while creating constructors will be exploiting prototype property of a constructor.

JavaScript is sloppy, no doubt! But by following goods patterns you can write manageable code.