๐ŸŒ
Medium
heyjoshlee.medium.com โ€บ factory-functions-in-javascript-the-how-and-why-d8988bda654a
Factory Functions in Javascript: The How and Why | by Josh Lee | Medium
March 21, 2024 - A lot of experienced developers have opinions about using OOP versus something like functional programming. Thatโ€™s not something Iโ€™m going to discuss in this article. Anyway, after moving from primarily working with Ruby to Javascript, I wanted to see how OOP worked in Javascript. Turns out, OOP in Javascript is a bit different than working with Ruby. One of the most popular ways to work with objects in Javascript is to use factory functions.
๐ŸŒ
The Odin Project
theodinproject.com โ€บ lessons โ€บ node-path-javascript-factory-functions-and-the-module-pattern
Factory Functions and the Module Pattern | The Odin Project
The MDN documentation on destructuring assignment has some great examples and should be a good read for this concept. Now you may be thinking - where does closure come into all of this? Factories seem to be returning an object. This is where we can extend our User factory to add a few more variables and introduce โ€œprivateโ€ ones. Take a look at this, now: function createUser(name) { const discordName = "@" + name; let reputation = 0; const getReputation = () => reputation; const giveReputation = () => { reputation++; }; return { name, discordName, getReputation, giveReputation }; } const josh = createUser("josh"); josh.giveReputation(); josh.giveReputation(); // logs { discordName: "@josh", reputation: 2 } console.log({ discordName: josh.discordName, reputation: josh.getReputation() });
๐ŸŒ
Advanced R
adv-r.hadley.nz โ€บ function-factories.html
10 Function factories | Advanced R
10.1 Introduction A function factory is a function that makes functions. Hereโ€™s a very simple example: we use a function factory (power1()) to make two child functions (square() and cube()):...
design pattern in object-oriented programming
Factory (object-oriented programming) - Wikipedia
In object-oriented programming, a factory is an object for creating other objects; formally, it is a function or method that returns objects of a varying prototype or class from some method call, โ€ฆ Wikipedia
๐ŸŒ
Refactoring.Guru
refactoring.guru โ€บ home โ€บ design patterns โ€บ creational patterns
Factory Method
January 1, 2026 - However, the primary function of the company as a whole is still writing code, not producing programmers. Concrete Creators override the base factory method so it returns a different type of product. Note that the factory method doesnโ€™t have to create new instances all the time. It can also return existing objects from a cache, an object pool, or another source. This example illustrates how the Factory Method can be used for creating cross-platform UI elements without coupling the client code to concrete UI classes.
๐ŸŒ
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 - The function is more self-documenting because default values supply examples of expected input. IDEs and static analysis tools can use default values to infer the type expected for the parameter. For example, a default value of 1 implies that the parameter can take a member of the Number type. Using default parameters, we can document the expected interface for our createUser factory...
๐ŸŒ
Kyle Shevlin's Blog
kyleshevlin.com โ€บ what-is-a-factory-function
What is a Factory Function? | Kyle Shevlin
Factory functions help us quickly create objects. They make use of closures to have private values and functions, all while avoiding the `this` keyword. Learn how to use them in this article.
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ what-are-factory-functions-in-javascript
What are factory functions in JavaScript ? | GeeksforGeeks
January 9, 2024 - If we have complex logic, and we ... producing products. Example 1: We have a factory function that will produce new robots with a single logic....
๐ŸŒ
SitePoint
sitepoint.com โ€บ blog โ€บ es6 โ€บ quick tip: what are factory functions in javascript
Quick Tip: What Are Factory Functions in JavaScript โ€” SitePoint
November 11, 2024 - Sure, hereโ€™s a simple example of a factory function in JavaScript: function createPerson(name, age) { return { name: name, age: age, sayHello: function() { console.log('Hello, my name is ' + this.name); } }; } var person1 = createPerson('John', ...
๐ŸŒ
Patterns.dev
patterns.dev โ€บ vanilla โ€บ factory-pattern
Factory Pattern
Say that we need many users for our application. We can create new users with a firstName, lastName, and email property. The factory function adds a fullName property to the newly created object as well, which returns the firstName and the lastName.
๐ŸŒ
Atendesigngroup
atendesigngroup.com โ€บ articles โ€บ factory-functions-javascript
Factory Functions in JavaScript | Aten Design Group
<br /> function Address (param) {<br /> var self = {};</p> <p> if (param === 'dev'){<br /> self = {<br /> state: โ€˜Coloradoโ€™,<br /> saveToLog: function(){<br /> // write info to a log file<br /> }<br /> };<br /> } else {<br /> self = {<br /> state: 'Colorado'<br /> };<br /> }</p> <p> return self;<br /> }</p> <p>var devAddress = Address('dev');<br /> var productionAddress = Address();<br /> You can see in the example above that we can allow the object to fit the needs of parameters. In our development environment we add a method that can save information to a log file, whereas, our production version can be without this method and also be lighter in memory. This gives us a more granular way of controlling our object. Overall, factory functions are very future-proof, flexible and dynamic.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ what-are-javascript-factory-functions
What are JavaScript Factory Functions?
Factory functions are mainly used when the user wants to initialize the object of a class multiple times with some assigned value or static values. It makes the process easy since we just have to call this function and retrieve the new object created. In the below example, we have created a factory function that will return a new object whenever this function is called.
๐ŸŒ
Rip Tutorial
riptutorial.com โ€บ factory functions
JavaScript Tutorial => Factory Functions
The last line will give an error because the function formalName is closed inside the cowFactory function. This is a closure. Factories are also a great way of applying functional programming practices in JavaScript, because they are functions.
๐ŸŒ
LinkedIn
linkedin.com โ€บ pulse โ€บ factory-functions-javascript-nikhil-nishad
Factory Functions In JavaScript
April 18, 2023 - I will try to explain this function in two ways, initially with real world situation and then a technical one. #1 Think of a factory that produces cars. ๐Ÿš— The factory has a blueprint for each car model, and every time it needs to produce ...
Top answer
1 of 6
10

Basically I would distinguish 3 approaches to create an object in JS:

  • Class
  • Constructor
  • Factory

Here are 3 examples (considering your Rabbit's one)

// class
class Rabbit {
  constructor() {
    this.speed = 3; 
    // it would be so nice to have just 'static const speed = 3;' instead of
    // using constructor for that
  }
  getSpeed() {
    return this.speed;
  }
}
let rabbit1 = new Rabbit();

// constructor
function ConstructorRabbit(){ }
ConstructorRabbit.prototype.speed = 3;
ConstructorRabbit.prototype.getSpeed = function() {
  return this.speed;
};
let rabbit2 = new ConstructorRabbit();

// factory
const rabbitProto = {
  speed: 3,
  getSpeed() {
    return this.speed;
  }
};
function factoryRabbit () {
  return Object.create(rabbitProto);
}
let rabbit3 = factoryRabbit();

I'm not sure that there are so many pros to use only factory for creating objects, but probably I can single out the one. As mentioned in the article if we refer to very famous 'Design Patterns', so we should prefer object composition instead of class inheritance. And I'm totally agree with that postulate, thus returning back to JS and ES6 classes, we can say that prototype delegation may be better than class inheritance in some cases.

But also, we shouldn't forget this (as mentioned in the article as well) statement: "How itโ€™s implemented doesnโ€™t matter at all unless itโ€™s implemented poorly". And this one, I would say, is a really good one.

2 of 6
7

Many answers here suggest Constructor Functions, although the name of the questions has to do with Factory Functions.

Factory Functions look like the following:

const RabbitFactory = () => {
  const speed = 3;
  const getSpeed = () => speed;
  return { getSpeed }
}
const rabbit = RabbitFactory();
rabbit.getSpeed() // -> 3
rabbit.speed // -> undefined!

I like Factory functions more than Constructor function because:

  • You don't need to get messy with prototyping
  • You don't need to use the Object constructor
  • Gives you the ability to choose what is private and what is public in your factory
    (in my example, speed is private and this is a good practice. If you want to read the value of rabbit's speed, use the GetSpeed getter)
Top answer
1 of 8
190

The basic difference is that a constructor function is used with the new keyword (which causes JavaScript to automatically create a new object, set this within the function to that object, and return the object):

var objFromConstructor = new ConstructorFunction();

A factory function is called like a "regular" function:

var objFromFactory = factoryFunction();

But for it to be considered a "factory" it would need to return a new instance of some object: you wouldn't call it a "factory" function if it just returned a boolean or something. This does not happen automatically like with new, but it does allow more flexibility for some cases.

In a really simple example the functions referenced above might look something like this:

function ConstructorFunction() {
   this.someProp1 = "1";
   this.someProp2 = "2";
}
ConstructorFunction.prototype.someMethod = function() { /* whatever */ };

function factoryFunction() {
   var obj = {
      someProp1 : "1",
      someProp2 : "2",
      someMethod: function() { /* whatever */ }
   };
   // other code to manipulate obj in some way here
   return obj;
}

Of course you can make factory functions much more complicated than that simple example.

One advantage to factory functions is when the object to be returned could be of several different types depending on some parameter.

2 of 8
141

Benefits of using constructors

  • Most books teach you to use constructors and new

  • this refers to the new object

  • Some people like the way var myFoo = new Foo(); reads.

Drawbacks

  • Details of instantiation get leaked into the calling API (via the new requirement), so all callers are tightly coupled to the constructor implementation. If you ever need the additional flexibility of the factory, you'll have to refactor all callers (admittedly the exceptional case, rather than the rule).

  • Forgetting new is such a common bug, you should strongly consider adding a boilerplate check to ensure that the constructor is called correctly ( if (!(this instanceof Foo)) { return new Foo() } ). EDIT: Since ES6 (ES2015) you can't forget new with a class constructor, or the constructor will throw an error.

  • If you do the instanceof check, it leaves ambiguity as to whether or not new is required. In my opinion, it shouldn't be. You've effectively short circuited the new requirement, which means you could erase drawback #1. But then you've just got a factory function in all but name, with additional boilerplate, a capital letter, and less flexible this context.

Constructors break the Open / Closed Principle

But my main concern is that it violates the open/closed principle. You start out exporting a constructor, users start using the constructor, then down the road you realize you need the flexibility of a factory, instead (for instance, to switch the implementation to use object pools, or to instantiate across execution contexts, or to have more inheritance flexibility using prototypal OO).

You're stuck, though. You can't make the change without breaking all the code that calls your constructor with new. You can't switch to using object pools for performance gains, for instance.

Also, using constructors gives you a deceptive instanceof that doesn't work across execution contexts, and doesn't work if your constructor prototype gets swapped out. It will also fail if you start out returning this from your constructor, and then switch to exporting an arbitrary object, which you'd have to do to enable factory-like behavior in your constructor.

Benefits of using factories

  • Less code - no boilerplate required.

  • You can return any arbitrary object, and use any arbitrary prototype - giving you more flexibility to create various types of objects which implement the same API. For example, a media player that can create instances of both HTML5 and flash players, or an event library which can emit DOM events or web socket events. Factories can also instantiate objects across execution contexts, take advantage of object pools, and allow for more flexible prototypal inheritance models.

  • You'd never have a need to convert from a factory to a constructor, so refactoring will never be an issue.

  • No ambiguity about using new. Don't. (It will make this behave badly, see next point).

  • this behaves as it normally would - so you can use it to access the parent object (for example, inside player.create(), this refers to player, just like any other method invocation would. call and apply also reassign this, as expected. If you store prototypes on the parent object, that can be a great way to dynamically swap out functionality, and enable very flexible polymorphism for your object instantiation.

  • No ambiguity about whether or not to capitalize. Don't. Lint tools will complain, and then you'll be tempted to try to use new, and then you'll undo the benefit described above.

  • Some people like the way var myFoo = foo(); or var myFoo = foo.create(); reads.

Drawbacks

  • new doesn't behave as expected (see above). Solution: don't use it.

  • this doesn't refer to the new object (instead, if the constructor is invoked with dot notation or square bracket notation, e.g. foo.bar() - this refers to foo - just like every other JavaScript method -- see benefits).

๐ŸŒ
YouTube
youtube.com โ€บ colorcode
What is Factory Function in JavaScript - in 1 minute - YouTube
Factory Functions are an incredibly useful tool in JavaScript. It's a design pattern that's used in many languages. In this one minute coding video I will ex...
Published ย  February 2, 2021
Views ย  11K
๐ŸŒ
DEV Community
dev.to โ€บ snevy1 โ€บ classes-vs-factory-functions-in-javascript-4fjn
Classes vs Factory functions in Javascript - DEV Community
November 30, 2023 - Once you call the function, it sets up and returns a new object. Below is how we would implement a factory function:
๐ŸŒ
DEV Community
dev.to โ€บ bchau โ€บ factory-functions-vs-constructors-500m
Factory Functions vs Constructors - DEV Community
April 27, 2022 - In the example above, the constructor function looks a lot like a factory function, except for the use of the keyword "this"."this" refers to the constructor function that created the instance object. In other words, "this" has no value in a constructor function.