DEV Community

Cover image for JS factory pattern
Alex Alencar
Alex Alencar

Posted on

1

JS factory pattern

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

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️