Sub topic 10
Building Objects with Factory Functions
This chapter assumes you know how closures create private state, which the previous chapter covered. You should also be comfortable with object literals, shorthand methods, and the spread operator.
A factory function is a plain function that builds and returns a new object. It is not a constructor, so you call it without new. Each call runs the function body again, which creates a fresh set of local variables. The returned object's methods close over those variables. As a result, every object gets its own private state.
A Worked Example
The factory below builds a to-do list. The items array and the nextId counter are local to each call, so outside code can reach them only through the returned methods.
function createTodoList(owner) {
const items = [];
let nextId = 1;
return {
owner,
add(text) {
const item = { id: nextId++, text, done: false };
items.push(item);
return item.id;
},
complete(id) {
const item = items.find((i) => i.id === id);
if (item) item.done = true;
return Boolean(item);
},
list() {
return items.map((i) => ({ ...i }));
}
};
}
const work = createTodoList('Ana');
const home = createTodoList('Ben');
const id = work.add('Write report');
home.add('Buy milk');
work.complete(id);
console.log(work.list()); // [ { id: 1, text: 'Write report', done: true } ]
console.log(home.list()); // [ { id: 1, text: 'Buy milk', done: false } ]
console.log(work.items); // undefinedThe work and home lists each start their ids at 1 because each call created a separate nextId. The list method returns copies, so a caller who mutates the result cannot change the internal array.
Methods That Do Not Depend on this
The methods reach state through the closure, not through this. You can pull them off the object and pass them around, and they still work:
const { add } = work;
add('Call client'); // works, no binding neededThe same move with a class method that uses this would throw a TypeError, because this is undefined once the method is detached from its object.
Common Errors
- Exposing state by accident. If you return
itemsdirectly, or a property that holds it, callers can mutate it. Return copies or derived values. - Reassigning a primitive on the object. In the example,
owneris copied onto the object when it is created. Changingwork.ownerlater does not change anything the methods read. Keep data that methods depend on in the closure. - Using
new. Callingnew createTodoList()still returns your object, because an explicitly returned object replaces the onenewcreates. It only misleads readers, so leavenewout.
Factories Versus Classes
| Concern | Factory function | Class |
|---|---|---|
| Truly private state | Yes, through closure | Yes, with `#fields` |
| Method memory | One copy of each method per object | Methods shared on the prototype |
| `instanceof` checks | Not supported | Supported |
| Detached methods | Work as-is | Need `bind` or arrow fields |
Exercise
Write a factory createStopwatch() that returns an object with tick(), which adds one to a hidden elapsed count, reset(), which sets it back to zero, and read(), which returns the count. Two stopwatches must not share a count.
Show answer
function createStopwatch() { let elapsed = 0; return { tick() { elapsed += 1; }, reset() { elapsed = 0; }, read() { return elapsed; } }; } Each call declares a new elapsed, so const a = createStopwatch(); const b = createStopwatch(); a.tick(); a.tick(); b.tick(); gives a.read() === 2 and b.read() === 1.
Exercise
Why does const { list } = work; list(); still return the to-do items, when the equivalent class method using this.items would fail?
Show answer
list finds items through its closure over the factory call's environment. It never reads this, so detaching it from the object changes nothing.