Learning Javascript : Object Creation Patterns
There are majorly Four patterns to create an Object in Javascript.
- Constructor Pattern.
- Factory Pattern
- Prototype Pattern
- Dynamic Prototype Pattern.
Constructor Pattern –Â http://jsbin.com/rejaca/3/edit?js,output
- Use this keyword to attach
- Don’t return anything.
var  testerConstructor = function(name,age,type){
 // this - current Object is used.
 this.name  = name;
  this.age = age;
  this.type = type;
  this.printTester = function(){
    console.log('Tester Name  :  ' + this.name+ " - Age - "+this.age+' Type - '+this.type);
  }
}
var promode =Â Â new testerConstructor('Promode','26','Full Stack Tester');
var amit =Â Â new testerConstructor('Amit','26','Manual');
promode.printTester();
amit.printTester();
Factory Pattern –Â http://jsbin.com/rejaca/edit?js,console
- Create Dummy Object
- Return this object afterÂ
var  testerFactory = function(name,age,type){
  var temp = {};  // Object is create internallyÂ
  temp.name  = name;
  temp.age = age;
  temp.type = type;
  temp.printTester = function(){
    console.log('Tester Name  :  ' + this.name+ " - Age - "+this.age+' Type - '+this.type);
  }
  return temp;  Â
}
var promode =Â Â Â testerFactory('Promode','26','Full Stack Tester');
var amit =Â Â Â testerFactory('Amit','26','Manual');
promode.printTester();
amit.printTester();
Prototype Pattern
- Put things in Shared space (Prototype).
- Kind of assign default values.
var testerPrototpye = function(){};
testerPrototpye.prototype.name = 'default';
testerPrototpye.prototype.age = '25';
testerPrototpye.prototype.type = 'Manual';
testerPrototpye.prototype.printTester = function(){
  console.log(' Here is Your Tester '+ this.name + ' - ' + this.age + ' - ' +this.type );
};
var j = new testerPrototpye();
j.name = 'JM';
j.age = '28';
j.printTester();
Dynamic Prototype Pattern. –Â http://jsbin.com/tajiwof/edit?js,console
// Dynamic Prototype Pattern  – Object Creation
var tDynamicProto = function(name,age){
  this.name = name;
  this.age = age;
  if( typeof this.printMe !== 'function'){
    tDynamicProto.prototype.printMe = function(){
      console.log('Hi => ' + this.name + ' - '+this.age);
    }
  }
}
var jm = new tDynamicProto('JM',23);
jm.printMe();
Lexical ScopingÂ
Inner Function Automatically has the Outside variables access.
// Lexical Scoping  – Inner Functions have access to OUTER Variables
var t = 12;
var tt = function(){
  var  temp = 12;
  return temp+t;
}
console.log(tt());
console.dir(tt);
Closure in Javascript
var manual = function(age){
var testerAge = function(age2){
 return age2+age;
  };
  return testerAge;
};
var p = new manual(1);
console.log(p(2));

