How to Create a Constructor in JavaScript

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:

  1. function Programmer(id,name)  
  2. {  
  3.    this.id = id;  
  4.    this.name = name;  
  5.    this.describe = function(){console.log(this.name + “ hates javascript!”);}  
  6. }  
  7. var m = new Programmer(“Bill”,420);  
  8. 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:
  1. function Programmer(id,name)  
  2. {  
  3.    //creates an empty object viz this  
  4.    //var this = {};  
  5.    this.id = id;  
  6.    this.name = name;  
  7.    this.describe = function(){console.log(this.name + “ hates javascript!”);}  
  8.    //insert all properties/mehotds of prototype object into this  
  9.    //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.

Ebook Download
View all
Learn
View all