UX Design and Development course

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?


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";
   // 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.

Some people prefer to use factory functions for everything just because they don't like having to remember to use new (EDIT: and this can be a problem because without new the function will still run but not as expected). I don't see that as an advantage: new is a core part of the language so to me deliberately avoiding it is a bit arbitrary - might as well avoid other keywords like else.

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