Sub topic 10
Building Objects with Factory Functions
A factory function is an ordinary function that builds a new object and returns it. You call it without new. Each call runs the function body again, so each call also creates a new lexical environment. Methods defined inside the factory close over that environment, so every object it returns gets its own private state. This chapter covers how to design factories, how they compare with classes, and the mistakes developers make most often with them.
This chapter assumes you already know how a closure keeps a variable alive after its outer function returns, and how that gives you private state. It also assumes you are comfortable with object literals, spread syntax, and the basics of class.
The Basic Shape
A factory takes configuration as parameters and declares private variables. It then returns an object whose methods use those variables.
function createTodoList(owner) {
if (typeof owner !== 'string' || owner === '') {
throw new TypeError('owner must be a non-empty string');
}
const items = [];
function add(text) {
items.push({ text, done: false });
return items.length;
}
function complete(index) {
if (index < 0 || index >= items.length) {
throw new RangeError(`No item at index ${index}`);
}
items[index].done = true;
}
function list() {
return items.map((item) => ({ ...item }));
}
function remaining() {
return items.filter((item) => !item.done).length;
}
return { owner, add, complete, list, remaining };
}
const work = createTodoList('Ana');
work.add('Write report');
work.add('Review PR');
work.complete(0);
console.log(work.remaining()); // 1
console.log(work.list()); // [ { text: 'Write report', done: true }, { text: 'Review PR', done: false } ]
console.log(work.items); // undefinedThe factory follows a few conventions:
- It checks its input before building anything, so it never returns an invalid object.
- It defines the methods as named inner functions and then lists them in the returned object. This makes the public interface easy to read in one line.
owneris copied onto the object as a plain property. Changingwork.ownerlater has no effect on the private state, because the methods never read that property.
Each Call Gets Its Own Environment
Every call to createTodoList creates a fresh items array and a fresh set of method functions. Those functions are tied to that call's environment.
You can confirm that the instances are separate, and that their methods are separate function objects:
function createTodoList(owner) {
const items = [];
return {
owner,
add(text) { items.push(text); return items.length; },
count() { return items.length; }
};
}
const work = createTodoList('Ana');
const home = createTodoList('Ben');
work.add('a');
work.add('b');
home.add('c');
console.log(work.count()); // 2
console.log(home.count()); // 1
console.log(work.add === home.add); // falseThe last line has a cost. Class methods live once on a shared prototype. Factory methods are created again for each instance. The section on trade-offs below covers when that cost matters.
Methods That Do Not Depend on this
The methods read their state through closure, not through this. As a result, you can detach them, pass them as callbacks, or destructure them, and they keep working.
function createCounter() {
let count = 0;
return {
increment() { count += 1; return count; },
value() { return count; }
};
}
const counter = createCounter();
const { increment } = counter;
increment();
[1, 2, 3].forEach(increment);
console.log(counter.value()); // 4A class method that uses this fails in the same situation:
class Counter {
#count = 0;
increment() { this.#count += 1; return this.#count; }
}
const c = new Counter();
const detached = c.increment;
try {
detached();
} catch (err) {
console.log(err.name); // TypeError
}Class bodies run in strict mode, so this inside detached() is undefined. With classes you need .bind(this), an arrow-function class field, or a wrapper. A factory does not need any of these.
Composing Behavior
Factories make it easy to combine behavior. You don't need inheritance. Small functions each add one capability over shared private state, and the main factory merges them together.
function canEat(state) {
return {
eat(amount) {
state.energy += amount;
return state.energy;
}
};
}
function canSleep(state) {
return {
sleep(hours) {
state.energy += hours * 2;
return state.energy;
}
};
}
function canRun(state) {
return {
run(distance) {
if (state.energy < distance) {
return `${state.name} is too tired`;
}
state.energy -= distance;
return `${state.name} ran ${distance}`;
}
};
}
function createDog(name) {
const state = { name, energy: 0 };
return Object.freeze({
...canEat(state),
...canSleep(state),
...canRun(state),
get energy() { return state.energy; }
});
}
const rex = createDog('Rex');
rex.eat(3);
rex.sleep(2);
console.log(rex.run(5)); // Rex ran 5
console.log(rex.energy); // 2
console.log(rex.run(5)); // Rex is too tiredstate is never put on the returned object. Every capability closes over the same state object, so they all share it. Object.freeze stops callers from replacing or adding methods. The private state can still change, because freezing applies only to the returned object.
Common Errors
State Declared Outside the Factory
If you move a variable outside the factory, every instance shares it.
let count = 0; // wrong place
function createCounter() {
return { increment() { count += 1; return count; } };
}
const a = createCounter();
const b = createCounter();
a.increment();
console.log(b.increment()); // 2, not 1The fix is to declare count inside createCounter. Per-instance state must live in the body of the factory, because the body is the part that runs again on each call.
Leaking a Reference to Private Data
Returning a private array or object directly hands the caller a live handle to it. The caller can then change your "private" state.
function createRoster() {
const names = [];
return {
add(name) { names.push(name); },
all() { return names; } // leaks the real array
};
}
const roster = createRoster();
roster.add('Kim');
roster.all().length = 0;
console.log(roster.all()); // [] — private data was wipedReturn a copy instead, such as [...names] or structuredClone(names) for nested data. You can also return a frozen copy. createTodoList copies each item for the same reason.
Using this Inside Factory Methods
Writing this.items in a factory method brings back the binding problems that factories avoid, and it requires the data to be public. Read from closed-over variables instead.
Expecting instanceof to Work
A factory returns a plain object, so instanceof has no constructor to test against. Check for behavior instead, for example with typeof obj.add === 'function'. If you need real type checks, use a class.
Factories Versus Classes
| Concern | Factory function | Class |
|---|---|---|
| Privacy | Closure variables, cannot be accessed from outside | `#private` fields, enforced by the language |
| Method memory | New function objects for each instance | Shared on the prototype |
| Detached methods | Work without binding | Need `bind` or arrow fields if they use `this` |
| `instanceof` | Not supported | Supported |
| Code reuse | Composition by merging capabilities | `extends` and `super` |
| Calling syntax | `createX()` | `new X()` |
Use a factory when objects need private state, when callers will pass methods around as callbacks, or when you want to build objects from small capabilities. Use a class when you create very large numbers of instances, because a million objects with five methods each means five million function objects. A class is also the better choice when you need instanceof, or when a framework expects constructors. In modern engines, the per-instance cost does not matter for hundreds or thousands of objects. Measure before you switch.
Exercise
This factory is meant to give each wallet its own balance, but two wallets interfere with each other. Explain why and fix it. let balance = 0; function createWallet() { return { deposit(n) { balance += n; return balance; } }; }
Show answer
balance is declared at module level, so every wallet's deposit closes over the same single variable. Move the declaration into the factory so that each call creates its own binding: function createWallet() { let balance = 0; return { deposit(n) { balance += n; return balance; } }; }.
Exercise
A factory returns { getTags() { return tags; } }, where tags is a private array. What can go wrong, and what is a safe version?
Show answer
The caller receives the real array and can push to it, splice it, or clear it, which bypasses any validation in the factory. Return a copy instead, for example getTags() { return [...tags]; }, or Object.freeze([...tags]) if you want attempts to change the copy to fail.
Exercise
Will const { increment } = createCounter(); increment(); work for a factory whose methods use closure variables? Would the same destructuring work for a class method that reads this.#count?
Show answer
It works for the factory, because increment reads count through its closure and never uses this. For the class, the detached method runs with this set to undefined, so reading this.#count throws a TypeError unless the method is bound or defined as an arrow-function field.