How to Create a Constructor in JavaScript

Introduction

 
Constructors in JavaScripts! Sounds odd. Right?
 
But yes Constructors in JavaScripts are widely used by developers nowadays. 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.     this.id = id;  
  3.     this.name = name;  
  4.     this.describe = function () {  
  5.         console.log(this.name + “hates javascript!”);  
  6.     }  
  7. }  
  8. var m = new Programmer(“Bill”, 420);  
  9. console.log(m); //{id: 420, name: “Bill”, describe: function()} 
Note: Capital P in Programmer, this is the notion used for constructors, first capital alphabet.
 
The above code creates an object and assigns appropriate values to it using the 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 a new keyword as
  1. function Programmer(id, name) {  
  2.     //creates an empty object viz this    
  3.     //var this = {};    
  4.     this.id = id;  
  5.     this.name = name;  
  6.     this.describe = function () {  
  7.         console.log(this.name + “hates javascript!”);  
  8.     }  
  9.     //insert all properties/mehotds of prototype object into this    
  10.     //return this;    
That simple
 
Another thing which you will want to consider while creating constructors will be exploiting the prototype property of a constructor.
 
JavaScript is sloppy, no doubt! But by following goods patterns you can write manageable code.