Javasrcipt Object Creation Pattern

 Factory Pattern

var peopleFactory = function(name,age,state){
var temp ={}

temp.age=age;
temp.name=name;
temp.state=state;

temp.printPerson = function(){
console.log(this.name+","+this.age + ","+ this.state)
}
return temp;
}

var person1 = peopleFactory('john',23,'CA');
var person2 = peopleFactory('himanshu',23,'CA');

person1.printPerson();
person2.printPerson();

 Cosntructor Pattern

var peopleConstructor = function(name,age,state){


this.age=age;
this.name=name;
this.state=state;

this.printPerson = function(){
console.log(this.name+","+this.age + ","+ this.state)
}

}

var person1 = new peopleConstructor('john',23,'CA');
var person2 = new peopleConstructor('himanshu',23,'CA');

person1.printPerson();
person2.printPerson();

 

Everything is good with constructor patter the only problem is that if we create 1000 objects with it than I have to still write this.printPerson which is not good. So the next pattern which is prototype pattern claims to fix this

 

Few Properties 

 Evert element has a constructor by default and it is assigned by javascript. So if we console.log person1.constructor we will get back the original cosntructor which is

 function(name,age,state){ this.age=age; this.name=name; this.state=state;

this.printPerson = function(){ console.log(this.name+","+this.age + ","+ this.state) }

 } 

 Similarly we will get Object Array Function if we assign them emptly and try to extract their constrcutor

 

prototype Pattern

 Here instead of creating a function with all propertty we will be creating first a empty function.It doesnt't directly reside in it but has access to it.

The main use case of the prototype is that lets suppose we have to create 100000 copy of the object and if it has the same function which is same than it is just a waste of memory so we will use prototype instead of it. So what is prototype-

Every class/constructor has a protottpe property that is shared by every instance of the constructor/class. So it can be accessed by anybody. In the constructor above the printPerson is common for all


var peopleConstructor = function(name,age,state){


this.age=age;
this.name=name;
this.state=state;


peopleConstrcutor.prototype.country = "india

peopleConstructor.prototype.printPerson = function(){
console.log(this.name+","+this.age + ","+ this.state)
}

var person1 = new peopleConstructor('john',23,'CA');
var person2 = new peopleConstructor('himanshu',23,'CA');

person1.printPerson();
person2.printPerson();

 

Properties

 First it will check in instance and if it is not there than it will check it in prototype

Also all array or string has prototype which are the methods of them and all has the construtor function



Comments

Popular posts from this blog

Form Part 2

Event mini project by Thapa#33

De-mystifying 'this' keyword of Javascript