Skip to content
Advertisement

Constructor function vs Factory functions

Can someone clarify the difference between a constructor function and a factory function in Javascript.

When to use one instead of the other?

Advertisement

Answer

The basic difference is that a constructor function is used with the new keyword (which causes JavaScript to automatically create a new object, set this within the function to that object, and return the object):

var objFromConstructor = new ConstructorFunction();

A factory function is called like a “regular” function:

var objFromFactory = factoryFunction();

But for it to be considered a “factory” it would need to return a new instance of some object: you wouldn’t call it a “factory” function if it just returned a boolean or something. This does not happen automatically like with new, but it does allow more flexibility for some cases.

In a really simple example the functions referenced above might look something like this:

function ConstructorFunction() {
   this.someProp1 = "1";
   this.someProp2 = "2";
}
ConstructorFunction.prototype.someMethod = function() { /* whatever */ };

function factoryFunction() {
   var obj = {
      someProp1 : "1",
      someProp2 : "2",
      someMethod: function() { /* whatever */ }
   };
   // other code to manipulate obj in some way here
   return obj;
}

Of course you can make factory functions much more complicated than that simple example.

One advantage to factory functions is when the object to be returned could be of several different types depending on some parameter.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement