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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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
1 2 3 4 5 6 7 8 | var t = 12; var tt = function(){ var temp = 12; return temp+t; } console.log(tt()); console.dir(tt); |
Closure in Javascript
1 2 3 4 5 6 7 8 9 10 | var manual = function(age){ var testerAge = function(age2){ return age2+age; }; return testerAge; }; var p = new manual(1); console.log(p(2)); |