Often in Javascript, you only want one instance of an object. In classical OOP this is done with a singleton design pattern. In javascript we simply use the object literal (i.e. { property: ‘value’}). But when we need a multitude of similar objects, javascript gives us two ways to do it. With a factory function, or a constructor. But which one should you use?
Factories
A factory is a design pattern that’s handed to us from the classical OOP world. In it, a function (method, property, what ever.) is given the responsibility to create objects (from a class). Based on parameters the factory method might decided to use different classes or subclasses to construct a similar object, allowing for some extra flexibility. Because javascript doesn’t have classes, we don’t even have the option to create an object based on a class. The factory method will thus have to start with a clean object, and add properties to it:
function createCar() {
var car = {}
car.start = function () { /* Code goes here */ };
car.stop = function () { /* Code goes here */ };
return car;
}
var myCar = createCar();
Constructors
Constructors are a bit like classes in other languages, but are far more dynamic. They also lack the classical OOP features, such as inheritance and variable visibility. If you want any of those in javascript, you have to use a design pattern such as the caller extension pattern. The car object we’ve created above can also be created in a constructor:
function Car() {
this.start = function () { /* Code goes here */ };
this.stop = function () { /* Code goes here */ };
}
var myCar = new Car();
As you can see, it saves a few lines of code. Also note that unlike the factory, the name of the constructor is capitalized. This is considered to be a best practice, as it makes it clear in what way the function should be invoked. It’s also in line with the native constructors javascript provides such as Object and Array.
Factories or constructors
The following table summarizes the differences in the two approaches to object creation.
| Factory | Constructor | |
|---|---|---|
| Extending and inheritance | Impossible | Prototype or Caller extension pattern |
| Takes advantage of prototype | No | Yes |
| Language features | None | Gets the constructor property and can be tested by instanceof. |
| Code clarity | Difficult to distinguish from other functions | Can be distinguished because of capital convention and the ‘new’ keyword |
| Performance | Slower | Faster |
In most cases, as we can see, using a constructor is the better option. It is much clearer and allows you to make use of a few features of javascript that aren’t available to objects created with a factory method. The only real advantage to be gained from a factory method is that objects made with a factory can not be influenced by a prototype.