DEV Community

loading...
Cover image for JS factory pattern

JS factory pattern

aalencar profile image Alexandre Alencar ・1 min read

After reading more about the Factory Method design pattern I wanted to know how it would work with JS and what are the benefits. Turns out that this design pattern doesn't provide more benefits over class creation or constructor functions. The only thing that changes is how the this is handled.

/*
 Constructor function
 - implicitly returns this
 - must be called with new keyword
function Dog(name) {
  this.name = name;
}

const dog = new Dog('joe');

/* 
  Class
  - desugars to a constructor function
  - must be called with new keyword
*/
class Dog() {
  constructor(name) {
    this.name = name;
  }
}

const dog = new Dog('joe');

/*
  Factory
  - must return an object
  - called as a regular function without new keyword
*/

function Dog(name) {
  return { name }
}

const dog = Dog('joe');

Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide