Wednesday, 7 March 2018

JavaScript object created pattern

1) Factory pattern-

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

   var temp = {};
   temp.name = name;
   temp.age = age;
   temp.state = state;
 
   temp.ShowDetails = function(){
     console.log(temp.name +" "+ temp.age +" "+ temp.state);
   }
 
   return temp;
};

var person1 = new personfactory('Ashish',34,'In');
var person2 = new personfactory('Soni',30,'Au');

person1.ShowDetails(); //Ashish 34 In

person2.ShowDetails(); Soni 30 Au

2)- Constructor pattern

var personConstructor = function(name, age){

    this.name = name;
    this.age = age;
 
    this.getDetails = function(){
      console.log(this.name + " " + this.age);
    }
};

var Male = new personConstructor('Ashish',34);
var Female = new personConstructor('geeta',30);

Male.getDetails();  //Ashish 34
Female.getDetails(); //geeta 30

3)- Prototype pattern

var person = function(){

};

  person.prototype.name ="no name";
  person.prototype.age = 0;
  person.prototype.state = "no state";
  person.prototype.showDetails = function(){
  console.log(this.name +" "+ this.age +" "+ this.state);
};

var male = new person();
male.name = "Ashish";
male.age = 34;
male.state = "UP";
male.showDetails(); // Ashish 34 UP

var female = new person();
female.name = "Sonam";
female.age = 30;
female.state = "MP";

female.showDetails();  // Sonam 30  MP

//case1 - female.name = "Sonam"; not commented this line
console.log('name' in female); //true
console.log(female.hasOwnProperty('name')); //true

//case2 - female.name = "Sonam"; is commented this line then it also gives true because it look up property in person object
console.log('name' in female); //true
console.log(female.hasOwnProperty('name')); //false

//case3 - blabla is not having any property with this name either in female or person object
console.log('blabla' in female); //false

note: if comment  //female.name = "Sonam";
then female.showDetails();  will print-  no name 30  MP

4) dynamic prototype pattern

var dynamicPerson = function(name, age, state){
    this.name = name;
    this.age = age;
    this.state = state;
   
    if(typeof this.showDetails !== 'function'){
       dynamicPerson.prototype.showDetails = function(){
         console.log(this.name +" "+ this.age +" "+ this.state);
       };
    }
};

var male = new dynamicPerson('Ashish',34,'Up');
male.showDetails();  //Ashish 34 Up


No comments:

Post a Comment