I'm slightly unclear what you mean by "factory function" โ€” whether you mean a traditional JavaScript constructor function that gets called as new Person(), or a function that returns an object (literal?) that gets called as Person. If the former, I'll address it below. If the latter, then read on. Either way, I think the big reason to recommend classes is that they probably do the right thing with less syntactic noise. Classes vs Factories Consider a factory function like export function Person(name, age, gender) { return { name, age, gender }; } (using the newer shorthand object notation). So we can instantiate an object as let alice = Person('Alice', 44, 'female'); For one, we can't use instanceof. alice instanceof Person // false Small, but that's one difference โ€” there's nothing tying the values back to the factory. But now consider if we wanted to include a method in our object, e.g., format to print a description of the person. We might be tempted to say export function Person(name, age, gender) { return { name, age, gender, format() { return `${this.name} is ${this.age} years old and ${this.gender}.` } }; } This will function correctly, but there's a problem. let alice = Person('Alice', 44, 'female'); let bob = Person('Bob', 44, 'male'); alice.format === bob.format // false They have different function instances for their format methods โ€” in fact every object returned by Person will have a fresh function created for format. Those are a complete waste of memory, because we could use a single function instance for all of them. But it's messier to say. function format() { return `${this.name} is ${this.age} years old and ${this.gender}.` } export function Person(name, age, gender) { return { name, age, gender, format }; } We need to create a single format function that we keep module-private, and include it in each person. That's annoying, and the definition of Person is spreading out. Classes do the right thing here automatically. So we could declare export class Person { constructor(name, age, gender) { this.name = name; this.age = age; this.gender = gender; } format() { return `${this.name} is ${this.age} years old and ${this.gender}.` } } and then let alice = Person('Alice', 44, 'female'); let bob = Person('Bob', 44, 'male'); alice.format === bob.format // true Classes vs Constructors In the end, classes are pretty much just syntactic sugar over prototypes and constructors, so they can do the same things. However, constructors have the same problem as factories โ€” the definition gets spread around. To declare a method with a constructor function you have to patch the constructor after declaring it. export function Person(name, age, gender) { this.name = name; this.age = age; this.gender = gender; } Person.prototype.format() { return `${this.name} is ${this.age} years old and ${this.gender}.` } Once again, classes do the same thing in one declaration with less noise. My Preference: Classes and Factories My preference is often to have a class to define the data type โ€” e.g., the Person class above. Then I'll create factory functions for various use cases in the application. So maybe I'd have export function createBlankPerson() { return new Person('', 0, 'unknown'); } export function createRandomPerson() { return new Person( SAMPLE_NAMES[randomInt(0, SAMPLE_NAMES.length)], randomInt(18, 100), SAMPLE_GENDERS[randomInt(0, SAMPLE_GENDERS.length)] ); } This way I have the Person class to define the shape and methods; it's constructor to create instances from name, age, and gender; and the convenient factory methods more more specific use-cases. Answer from javajunkie314 on reddit.com
๐ŸŒ
Patterns.dev
patterns.dev โ€บ vanilla โ€บ factory-pattern
Factory Pattern
In JavaScript, the factory pattern isnโ€™t much more than a function that returns an object without using the new keyword. ES6 arrow functions allow us to create small factory functions that implicitly return an object each time.
๐ŸŒ
DEV Community
dev.to โ€บ snevy1 โ€บ classes-vs-factory-functions-in-javascript-4fjn
Classes vs Factory functions in Javascript - DEV Community
November 30, 2023 - In this article, I will explain what classes, constructors and factory functions are and how to use them in various situations. In my previous article, I discussed extensively how creating objects by classes and constructors is better than object literal.Check it out here. If you know constructors then classes shouldn't be hard to grasp. Classes are a syntactic sugar of constructors in Javascript.
๐ŸŒ
DoFactory
dofactory.com โ€บ javascript โ€บ design-patterns โ€บ factory-method
JavaScript Factory Method Design Pattern
var Factory = function () { this.createEmployee = function (type) { var employee; if (type === "fulltime") { employee = new FullTime(); } else if (type === "parttime") { employee = new PartTime(); } else if (type === "temporary") { employee = new Temporary(); } else if (type === "contractor") { employee = new Contractor(); } employee.type = type; employee.say = function () { console.log(this.type + ": rate " + this.hourly + "/hour"); } return employee; } } var FullTime = function () { this.hourly = "$12"; }; var PartTime = function () { this.hourly = "$11"; }; var Temporary = function () { thi
๐ŸŒ
Medium
medium.com โ€บ @nile.bits โ€บ javascript-factory-design-pattern-a-comprehensive-guide-9266b726ee5c
JavaScript Factory Design Pattern: A Comprehensive Guide | by Nile Bits | Medium
July 8, 2024 - A creational design pattern called the Factory Design Pattern gives subclasses the ability to modify the kind of objects that are generated while still providing an interface for doing so in a super class.
๐ŸŒ
The Odin Project
theodinproject.com โ€บ lessons โ€บ node-path-javascript-factory-functions-and-the-module-pattern
Factory Functions and the Module Pattern | The Odin Project
ECMAScript 6 (released in 2015) introduced a new JavaScript feature called โ€œmodulesโ€, which are a set of syntax for importing and exporting code between different JavaScript files. For now, we will be talking more generally about the module pattern using IIFEs, which you will still see out in the wild. In a later lesson, we will cover using ES6 modules for similar purposes. A more helpful use of IIFEs is the pattern of wrapping โ€œprivateโ€ code inside an IIFE: the module pattern. This is often done with factory functions:
๐ŸŒ
Reddit
reddit.com โ€บ r/javascript โ€บ [askjs] is there any reason to use a class over a factory function?
r/javascript on Reddit: [AskJS] Is there any reason to use a class over a factory function?
November 10, 2022 -

Lets say I want to create an object that represents a person with the properties name, age, and gender.

Is there any objective reason I should use a class to represent this rather than just making a function `Person()` which creates the object?

Top answer
1 of 13
178
I'm slightly unclear what you mean by "factory function" โ€” whether you mean a traditional JavaScript constructor function that gets called as new Person(), or a function that returns an object (literal?) that gets called as Person. If the former, I'll address it below. If the latter, then read on. Either way, I think the big reason to recommend classes is that they probably do the right thing with less syntactic noise. Classes vs Factories Consider a factory function like export function Person(name, age, gender) { return { name, age, gender }; } (using the newer shorthand object notation). So we can instantiate an object as let alice = Person('Alice', 44, 'female'); For one, we can't use instanceof. alice instanceof Person // false Small, but that's one difference โ€” there's nothing tying the values back to the factory. But now consider if we wanted to include a method in our object, e.g., format to print a description of the person. We might be tempted to say export function Person(name, age, gender) { return { name, age, gender, format() { return `${this.name} is ${this.age} years old and ${this.gender}.` } }; } This will function correctly, but there's a problem. let alice = Person('Alice', 44, 'female'); let bob = Person('Bob', 44, 'male'); alice.format === bob.format // false They have different function instances for their format methods โ€” in fact every object returned by Person will have a fresh function created for format. Those are a complete waste of memory, because we could use a single function instance for all of them. But it's messier to say. function format() { return `${this.name} is ${this.age} years old and ${this.gender}.` } export function Person(name, age, gender) { return { name, age, gender, format }; } We need to create a single format function that we keep module-private, and include it in each person. That's annoying, and the definition of Person is spreading out. Classes do the right thing here automatically. So we could declare export class Person { constructor(name, age, gender) { this.name = name; this.age = age; this.gender = gender; } format() { return `${this.name} is ${this.age} years old and ${this.gender}.` } } and then let alice = Person('Alice', 44, 'female'); let bob = Person('Bob', 44, 'male'); alice.format === bob.format // true Classes vs Constructors In the end, classes are pretty much just syntactic sugar over prototypes and constructors, so they can do the same things. However, constructors have the same problem as factories โ€” the definition gets spread around. To declare a method with a constructor function you have to patch the constructor after declaring it. export function Person(name, age, gender) { this.name = name; this.age = age; this.gender = gender; } Person.prototype.format() { return `${this.name} is ${this.age} years old and ${this.gender}.` } Once again, classes do the same thing in one declaration with less noise. My Preference: Classes and Factories My preference is often to have a class to define the data type โ€” e.g., the Person class above. Then I'll create factory functions for various use cases in the application. So maybe I'd have export function createBlankPerson() { return new Person('', 0, 'unknown'); } export function createRandomPerson() { return new Person( SAMPLE_NAMES[randomInt(0, SAMPLE_NAMES.length)], randomInt(18, 100), SAMPLE_GENDERS[randomInt(0, SAMPLE_GENDERS.length)] ); } This way I have the Person class to define the shape and methods; it's constructor to create instances from name, age, and gender; and the convenient factory methods more more specific use-cases.
2 of 13
9
Class offers syntax sugar over construction and inheritance. It is never necessary, but can be useful in some contexts like building a library. The console will log things with their class name instead of just object and you can use instanceof to do some type checking with classes.
๐ŸŒ
DEV Community
dev.to โ€บ srishtikprasad โ€บ factory-design-pattern-in-javascript-1f6l
Factory Design Pattern in JavaScript - DEV Community
October 3, 2024 - A factory wraps the creation of a new instance, giving us more flexibility and control in a way we do it. Inside the factory we choose to create a new instance of a class using the new operator, or leverage closures to dynamically build a stateful object literal, or even return a different object type based on a particular condition.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ js-factory-pattern
JavaScript Object Oriented Patterns: Factory Pattern | DigitalOcean
January 23, 2019 - Now, we create a class that acts as an intermediary between the actual factories classes and the user.
Find elsewhere
๐ŸŒ
JavaScript Tutorial
javascripttutorial.net โ€บ home โ€บ javascript tutorial โ€บ javascript factory functions
JavaScript Factory Functions
October 6, 2023 - By using the factory function, you create any number of the person objects without duplicating code. When you create an object, the JavaScript engine allocates memory to it.
๐ŸŒ
JavaScript in Plain English
javascript.plainenglish.io โ€บ javascript-factory-functions-cbc5b744671b
How to Create Objects Using Factory Functions in JavaScript | by Jake Mills | JavaScript in Plain English
June 13, 2023 - I thought it would be fun to develop class-like objects to show the path to what we now know as JavaScript classes. This article will cover building an object using factory functions, followed by an article covering constructor functions and using the new operator to create the same objects, ...
๐ŸŒ
Vercel
javascriptpatterns.vercel.app โ€บ patterns โ€บ design-patterns โ€บ factory-pattern
Factory Pattern | JavaScript Patterns
Not really a pattern: In JavaScript, the factory pattern isn't much more than a function that returns an object without using the new keyword. ES6 arrow functions allow us to create small factory functions that implicitly return an object each time. However, in many cases it may be more memory efficient to create new instances instead of new objects each time. class ...
๐ŸŒ
O'Reilly
oreilly.com โ€บ library โ€บ view โ€บ learning-javascript-design โ€บ 9781449334840 โ€บ ch09s10.html
The Factory Pattern - Learning JavaScript Design Patterns [Book]
July 8, 2012 - Imagine that we have a UI factory where we are asked to create a type of UI component. Rather than creating this component directly using the new operator or via another creational constructor, we ask a Factory object for a new component instead.
Author ย  Addy Osmani
Published ย  2012
Pages ย  254
๐ŸŒ
Medium
medium.com โ€บ @thebabscraig โ€บ javascript-design-patterns-part-1-the-factory-pattern-5f135e881192
JavaScript Design Patterns Part 1: The Factory Pattern | by Babs Craig | Medium
November 23, 2018 - This pattern, is called the Factory Pattern and it allows us to easily create objects in JavaScript. Coming from other OOP, class-based languages, one might be tempted to think that what weโ€™ll be doing in the lines of code below is creating classes and instances but in reality this is just syntactic sugar made to look like syntax from a class based language.
๐ŸŒ
Rob Dodson
robdodson.me โ€บ posts โ€บ javascript-design-patterns-factory
JavaScript Design Patterns: Factory - Rob Dodson
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Top answer
1 of 4
9

You would use Object.create:

const animal = () => ({
  talk: function() {
    console.log(this.sound);
  }
});

const dog = () => Object.create(animal(), {
  sound: {
    value: "woof"
  }
});

// or...

const dog2 = () => {
  var someDog = Object.create(animal());
  someDog.sound = "woof";

  return someDog;
};

var someDog = dog();
someDog.talk();

var someDog2 = dog2();
someDog2.talk();

BTW, my opinion is that you should go with ES2015+ class/inheritance and leave the use of custom factories and Object.create for corner cases where you really need them:

class Animal {
  talk() {
    return console.log(this.sound);
  }
}

class Dog extends Animal {
  constructor() {
    super();
    this.sound = "woof";
  }
}

var dog = new Dog();
dog.talk();

2 of 4
4

I checked this issue because I decided to use Factory Functions instead of classes. I assume you have a general factory function, like Animal or Mammal, which has some characteristics (such as sound, like some suggested), and you want to inherit them and add some specific characteristic in another factory function.

Let's build an Animal factory function:

const Animal = ({color = "green", numberOfLegs = 4} = {}) => {
  const SetColor = (newColor) => {
    color = newColor;
  };
  const GetColor= () => color;
  const GetNumberOfLegs = () => numberOfLegs;
  const MakeSound = () => console.log("Screetch");
  return {
    GetColor,
    GetNumberOfLegs,
    MakeSound
  }
}
const newCreature = Animal({color: black, numberOfLegs: 3})
newCreature.MakeSound() // -> "Screetch"

And let's build a Dog factory function:

const Dog = ({name = "rex", color = "black", numberOfLegs = 4} = {}) => {
  const MakeSound = () => console.log("Woof Woof");
  const Roll = () => console.log(`${name} made a roll!`)
  return {
    MakeSound,
    Roll
  }
}
const sniffles = Dog({name: "sniffles", color: black, numberOfLegs: 4})
sniffles.MakeSound() // -> "Woof Woof"
sniffles.Roll() // -> "sniffles made a roll!"

What should I do if I want to inherit all the good things I get from Animal that I have already?
Using ES6 Spread Syntax helps us to achieve a very neat way of doing so:

const Dog = ({name = "rex", color = "black", numberOfLegs = 4} = {}) => {
  const anAnimal = Animal({color, numberOfLegs}); // used the Animal factory!
  const MakeSound = () => console.log("Woof Woof");
  const Roll = () => console.log(`${name} made a roll!`)
  return {
    ...anAnimal, // And That's where magic happens!
    MakeSound,
    Roll
  }
}
const sniffles = Dog({name: "sniffles", color: black, numberOfLegs: 4})
sniffles.GetNumberOfLegs() // -> 4
sniffles.MakeSound() // -> "Woof Woof"
sniffles.Roll() // -> "sniffles made a roll!"

So what actually happened?
In Dog factory we invoked the Animal factory into anAnimal, so anAnimal is now an object. In the object that Dog factory returns, we spread the anAnimal object, and after that added properties of Dog. If you give an Object two identical keys with different values, it will take the latter:

const someObject = {a: 1, b: 2, a: 3};
someObject // -> {a: 3, b: 2}

Therefore, you don't need to worry if Dog uses any keys that were given already from Animal, because they are overwritten.

๐ŸŒ
Medium
medium.com โ€บ javascript-scene โ€บ javascript-factory-functions-vs-constructor-functions-vs-classes-2f22ceddf33e
JavaScript Factory Functions vs Constructor Functions vs Classes | by Eric Elliott | JavaScript Scene | Medium
August 24, 2021 - If you start out exporting a constructor or class and users start using the constructor, then down the road you realize you need the flexibility of a factory, (for instance, to switch the implementation to use object pools, or to instantiate across execution contexts, or to have more inheritance flexibility using alternative prototypes), you canโ€™t easily do so without forcing a refactor on callers. Unfortunately, in JavaScript, switching from a constructor or class to a factory is a breaking change:
๐ŸŒ
DEV Community
dev.to โ€บ jsmanifest โ€บ the-power-of-factory-design-pattern-in-javascript-2bf8
The Power of Factory Design Pattern in JavaScript - DEV Community
March 19, 2022 - That is exactly what the factory pattern is when we translate it to code. Let's pretend we are building an MMORPG game where we will go over the parts that take advantage of this pattern and we will see how it benefits our applications. We will have a Game class, a Profile to create profiles when users open our software, and the four classes that profiles will create as characters for our users to choose:
๐ŸŒ
33jsconcepts
33jsconcepts.com โ€บ concepts โ€บ factories-classes
Factories & Classes - 33 JavaScript Concepts
A factory function is a regular function that returns a new object. A class is a blueprint that uses the class keyword and the new operator. Both achieve the same goal, but they work differently and have different strengths.
๐ŸŒ
Medium
medium.com โ€บ javascript-scene โ€บ javascript-factory-functions-with-es6-4d224591a8b1
JavaScript Factory Functions with ES6+ | by Eric Elliott | JavaScript Scene | Medium
August 24, 2021 - Thereโ€™s a lot more of this to come! Buy the Book | Index | < Previous | Next > A factory function is any function which is not a class or constructor that returns a (presumably new) object.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ what-are-factory-functions-in-javascript
What are factory functions in JavaScript ? | GeeksforGeeks
January 9, 2024 - In JavaScript, a factory function is a function that returns an object. It is a way of creating and returning objects in a more controlled and customizable manner.