mercredi 30 août 2017

A little bit confused of `new` keyword in factory design pattern in javascript?

In the following code

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

var temp = {}

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

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


   }

 return temp;
 }

var person1 = peopleFactroy('Mahmoud',21,'lA');
var person2 = peopleFactroy('Mohamed',26,'bt');

person1.printPerson();   //Mahmoud 21 lA
person2.printPerson();   //Mohamed 26 bt

I know it is okay not to use the new keyword as i am returning an object from the constructor function and creating any number of persons, each will have his own object.

Now my question is if i used new keyword in the above example when creating persons object what would be the difference? , i tried that and gives me the same results but are they truly the same concept so they produce the same results or they are technically different but produce the same results?

Aucun commentaire:

Enregistrer un commentaire