Posted on

Categories this post is in


As with all the JS stuff I post, if you see something that’s not right – or could be improved – please get in touch..

In a recent project I came across an issue where I needed to duplicate a function and use it multiple times, with each outputting something different. Here’s a simplified example.

function dog() {

function pig() {

When I started writing JS, especially at university, I would duplicate functions like the above example as I wasn’t sure how else to do it. I did a large animations project earlier in the year which helped me get to grips with the factory pattern in JS. A factory basically gave me the ability to use a function multiple times in different ways, without writing duplicate code. Lets look at an example..

var animal = function(animal, noise) {
  var actions = {};
  actions.animal = animal;
  actions.makeNoise = function() {
    return noise;
  return actions;

var pig = animal('pig', 'Oinkkk');
// Pig

var dog = animal('dog', 'Wooofff');
// Wooofff

In this example I’m creating a function which returns an object containing the makeNoise function, this is my factory. I then define two variables, pig and dog, these are duplicates of the animal function. After declaring these I am then able to access the makeNoise function which makes use of the provided arguments. Imagine we had a thousand animals and they all needed to make a noise, I could do something like this.

for(i=0;i<animals.length;i++) {
  var animals[i].name = animal();

Next I started looking into the differences between the Factory Pattern and the Constructor pattern.Both would have been suitable for the task and I was struggling to understand what was different. Here’s an example which uses a Constructor for my animals.

var Animal = function(animal, noise) {
  this.animal = animal;
  this.noise = noise;

Animal.prototype.speak = function(){
    return this.noise

var pig = new Animal('Pig', 'Oinkkk');
var dog = new Animal('Dog', 'Wooof' );

// Wooof

As far as I’m aware, the key difference is that the variables I created with the factory pattern are not related in any way. The correct term is that they’re immutable, which means unable to be changed. Say for example when a picks an option the JS has needs output the Animal name and then it’s noise. With the factory I am unable to make adjustments to the makeNoise function once the factory has been made, however with the constructor I can do something like the following.

Animal.prototype.speak = function(){
    return this.animal + ':' + this.noise
// Dog:Wooof

This is cool as it gives me the ability to change the functionality along the way, unlike the Factory which I can’t change.

If you’ve any comments please get in touch!

Worthy of Note

Worthy of Note is a site aimed at Web Designers & Developers. It offers a wide range of resources to help assist anyone in the web industry.