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));
