Videos
Factories create an object and returns it. That is about it. The object that is created stands alone and the best part about this is you can use that object and not be effected by what happens to the other objects. This is know as a 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; // to broke down.
car1.toggleEngine(); //running false
Constructors add code to the function so you have a link to the prototype of the object constructor. The nice part about this additional link is to use the functional shared technique which looks like 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 we can see after the objects were created they still were very much linked together.
To be clear you can still do the following and not effect the objects created by the constructor. With functional shared method and mask the prototype function given by the constructor. So there are not fully linked but they are linked through the 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
With a factory, you have complete freedom on the object to return, so you can choose one constructor or another based on your input data, or the time of the day, or even not constructing anything at all - when using a factory to return sigletons.
On the contrary a constructor basically instantiates an object with a specific prototype, which you can configure afterwards, in the body of the constructor function.