DEV Community

Cover image for Differences between the factory pattern and the constructor pattern in JavaScript.
Luigi Morel
Luigi Morel

Posted on

3 2

Differences between the factory pattern and the constructor pattern in JavaScript.

Repeating code is something that's avoidable when writing logic for a piece of software that you need to produce.
Abstracting logic is a strategy that can be employed to avoid the repeatition that could emanate.

By the end of this article, you'll have learnt how to;

  • Use the factory pattern
  • Use the constructor pattern
  • The difference between the constructor and factory patterns.

Factory pattern

A factory in programming describes a function that returns an object...

function myFunc() {
  let obj = {};
  return obj;
}

const newObj = myFunc();
Enter fullscreen mode Exit fullscreen mode

Factories can be used to set properties and methods on the objects that they return. In the code snippet below, the makeAnimal function is used to create other objects that represent animals. When using factories, property values are assigned to the returned object through the function's arguments.

function makeAnimal(name, legs, horns) {
  let animal = {};

  // Set properties for the animal object
  animal.name = name;
  animal.legs = legs;
  animal.horns = horns;

  return animal;
}

const newAnimal = makeAnimal('Cow', 4, 2);

console.log(newAnimal.name); // Output: Cow
console.log(newAnimal.legs); // Output: 4
console.log(newAnimal.horns); // Output: 2
Enter fullscreen mode Exit fullscreen mode

Factories can also be used to create default values for properties of the object to be returned.

function makeAnimal(name: string, legs: number, horns: number) {
  let animal = {};

  // Set properties for the animal object
  animal.name = name;
  animal.legs = legs;
  animal.horns = horns;
  animal.hasFur = true; //Every new object returned from this function will have the `hasFur` property and it's value will always be true unless it's changed.

  return animal;
}
t
const newAnimal = makeAnimal('Cow', 4, 2);

console.log(newAnimal.name); // Output: Cow
console.log(newAnimal.horns); // Output: true
Enter fullscreen mode Exit fullscreen mode

Constructor pattern

This is another pattern used to create objects in javascript. Like a factory, a constructor is a function that returns an object.
You could also declare
Refer to the code snippet below.

function Animal(name: string, legs: number, horns: number) {
  // Set properties for the animal object
  this.name = name;
  this.legs = legs;
  this.horns = true; //Default property
}

const newAnimal = new Animal('Cow', 4, 2);

console.log(newAnimal.name); // Output: Cow
Enter fullscreen mode Exit fullscreen mode

Or, there's a cooler way to declare constructors in Javascript with some syntaxical sugar:

class Animal {
  constructor(legs) {
    this.legs = legs;
    this.printLegs = function () {
      console.log('Animal has %d legs:', this.legs);
    },
      this.name = 'Animal';
  }
}

let animal = new Animal(4);

animal.printLegs();
//Output : Animal has 4 legs
Enter fullscreen mode Exit fullscreen mode
Differences between the constructors and factories
  1. Syntax.
    Factories do not use the new keyword whereas constructors do. Refer to the examples above.

  2. Constructors inherit from a prototype property and return true from instanceOf factoryFunction.
    Factories, on the other hand do not inherit a reference to the prototypeproperty and return false from instanceOf factoryFunction.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (1)

Collapse
 
luigimorel profile image
Luigi Morel

Thank you for reading!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay