Factories in JavaScript

3 January 2012 - Wrocław

In recent projects I've been working on, I tried to use dependency injection in JavaScript as much as possible. The idea is to create instances of objects in one place, an Application class or some other kind of initializer - instead of using new all over the code. However, sometimes you need to defer object instantation for some reason, for example:

This is easy to solve with factories: functions that create instances. I know it sounds a bit Java-like and enterprisy, but in JavaScript (and especially in CoffeeScript) it's really simple. Here are some examples:

audioPlayer = new AudioPlayersPool(10, -> new AudioPlayer)
# the pool will create 10 instances of the player

clock = new Clock
createCountdown = (seconds) -> new Countdown(clock, seconds)
# we don't know how many countdowns we'll need

createTask = (attributes) ->
  new Task(serverSide, gameWorld, clock, earth, cannon, attributes)
createGameSession = (attributes) ->
  new GameSession(serverSide, createTask, attributes)
game = new Game(serverSide, createGameSession)

The last example shows another advantage. Before refactoring and moving GameSession and Task creation outside of Game class, the initialization looked like this:

game = new Game(serverSide, gameWorld, clock, earth, cannon)

The first, refactored version is much better, because game only needs to create gameSessions, not to deal with clock or gameWorld directly. Introducing factories leads to passing more specialized dependencies to other objects. Often it means less dependencies as well. As a result, objects have less knowledge about other parts of the application - which seems to be a good thing.

I hope you'll find factories useful in your code too!

Further reading