Factory and Constructor Functions in JavaScript

Factory and Constructor Functions in JavaScript

In JavaScript, there are two ways of creating objects, namely

  1. Factory functions, and

  2. Constructor functions


const firstChild = {
  age: 2,
  weight: 11,
  speak() {
    console.log('Ma!')
  }
}

const secondChild = {
  age: 3,
  weight: 15,
  speak() {
    console.log('Papa!')
  }
}

As you can see, there's duplicate code in the above program which we must avoid at all cost. Let's solve this problem using factory function first and then using constructor function.

Factory function

function createChild(age, weight, firstWord) {
  return {
    age,
    weight,
    speak() {
      console.log(`${firstWord}!`);
    },
  };
}

const firstChild = createChild(2, 11, 'Ma');
const secondChild = createChild(3, 15, 'Papa');

Constructor function

function Child(age, weight, firstWord) {
  this.age = age;
  this.weight = weight;
  this.speak = function () {
    console.log(`${firstWord}!`);
  };
}

const firstChild = new Child(2, 11, 'Ma');
const secondChild = new Child(3, 15, 'Papa');

new does three things:

  1. create an empty object

  2. set this to point to the empty object

  3. return the object from the function


this is a reference to the object that is executing this piece of code. Note that by default, this points to the global object.

In the context of a browser, the global object is the window object. Whereas, in Node.js environment, the global object is the global object.