Factory pattern vs constructor pattern in javascript -


i saw tutorial pattern in javascript. tutorial left me few question.

as see factory , constructor produce same result. difference between both of them. use case scenarios each one.

factory pattern

function factorypattern(data) {   var factory = {};   factory.name = data.name;   factory.title = data.title;   factory.startdate = data.startdate;   return factory; } var factoryuse = factorypattern(jsonobj); 

constructor pattern

function constructorpattern(data) {   this.name = data.name;   this.title = data.title;   this.startdate = data.startdate; }  var constructoruse = new constructorpattern(); 

edit: explained @michael warner. factory method return immutable object has no link creater after created.

but in constructor patter have link them.

so having practical use case better understand why have object has link constructor.

factories create object , returns it. it. object created stands alone , best part can use object , not effected happens other objects. know singleton.

var car = function(){     var car = {};     car.running = false;     car.toggleengine = function(){         this.running = !this.running;     }     return car; };  car1 = car(); // running false car2 = car(); // running false car1.toggleengine(); // running true car2.toggleengine = undefined; // broke down. car1.toggleengine(); //running false 

constructors add code function have link prototype of object constructor. nice part additional link use functional shared technique looks this.

var car = function (){     this.running = false; }; car.prototype.toggleengine = function(){     this.running = !this.running; } var car1 = new car; //running false var car2 = new car; //running false  car2.toggleengine() //running true car.prototype.toggleengine = function(){}; car1.toggleengine() //running false 

as can see after objects created still linked together.

to clear can still following , not effect objects created constructor. functional shared method , mask prototype function given constructor. there not linked linked through constructors prototype.

var car1 = new car; //running false var car2 = new car; //running false  car2.toggleengine() //running true car2.toggleengine = function(){}; car1.toggleengine() //running true 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -