Sub topic 12
Pitfall: Shared Mutable State on Prototypes
This chapter assumes you already know how property lookup walks the prototype chain, how assignment creates a shadowing own property, and what new does when it links an instance to Constructor.prototype. Here we look at a bug those rules produce when the value on the prototype is an object, such as an array, a Map, or a plain configuration object.
The Symptom
Here is a shopping cart written as a constructor function. The author put the items array on the prototype next to the add method, because both looked like "things every cart has."
function Cart() {}
Cart.prototype.items = [];
Cart.prototype.add = function (item) {
this.items.push(item);
return this;
};
const mine = new Cart();
const yours = new Cart();
mine.add('apple');
console.log(yours.items); // ['apple']
console.log(mine.items === yours.items); // true
console.log(Object.hasOwn(mine, 'items')); // falseNobody added anything to yours, yet it contains 'apple'. Both carts have only one array between them, and that array lives on Cart.prototype.
Why It Happens: Reading Is Not Writing
The cause is the difference between assigning to a property and mutating the value a property holds.
this.items = [...]is an assignment. It writes tothis, which creates an own property and shadows the prototype's value.this.items.push(item)is not an assignment toitems. JavaScript first readsthis.items. That lookup misses on the instance and finds the array on the prototype. The code then callspushon that array and changes it in place.
The lookup rules never copy anything. A read hands you a reference to the one object that sits on the prototype, and every instance that reads through the chain gets the same reference.
The table below shows which common operations stay local to the instance and which reach the shared value.
| Operation (prototype holds the value) | Effect |
|---|---|
| `obj.count = 5` | Creates an own `count` on `obj`. Safe. |
| `obj.count++` | Reads `0` from the prototype, writes own `1`. Safe. |
| `obj.tags = [...obj.tags, 'x']` | Builds a new array and assigns it as an own property. Safe. |
| `obj.tags.push('x')` | Mutates the shared array. Leaks to every instance. |
| `obj.config.debug = true` | Assigns on the shared nested object. Leaks. |
| `obj.stats.count++` | Reads `stats` through the chain, then writes on the shared object. Leaks. |
| `delete obj.tags` | Deletes only an own property. It does nothing to the prototype's value. |
The rule of thumb: the assignment is local only if the property directly left of = is the one being looked up on obj. When a dot or method call comes after the inherited property, you are working on the shared object.
The Fix: Create Per-Instance State Per Instance
Prototypes should hold behavior (methods) and values that are truly shared. Anything that each instance owns and changes belongs on the instance, created when the instance is created.
With a constructor function, initialize it in the constructor body:
function Cart() {
this.items = []; // a new array for every call to new Cart()
}
Cart.prototype.add = function (item) {
this.items.push(item);
return this;
};
const mine = new Cart();
const yours = new Cart();
mine.add('apple');
console.log(yours.items); // []
console.log(Object.hasOwn(mine, 'items')); // trueWith class syntax, a class field does the same thing. The field initializer runs once per instance, so each instance gets its own array:
class Cart {
items = [];
add(item) {
this.items.push(item);
return this;
}
}
const a = new Cart().add('apple');
const b = new Cart();
console.log(b.items); // []When you build objects with Object.create, use a factory function that adds the own state after it links the prototype:
const cartMethods = {
add(item) {
this.items.push(item);
return this;
}
};
function createCart() {
const cart = Object.create(cartMethods);
cart.items = [];
return cart;
}
const c1 = createCart().add('pear');
const c2 = createCart();
console.log(c2.items); // []Edge Case: Defaults Objects
The same bug shows up when a prototype is used to supply default settings. This pattern is popular because unset options fall through to the defaults.
const defaults = {
retries: 3,
headers: { Accept: 'application/json' }
};
const request = Object.create(defaults);
request.retries = 5; // own property, safe
request.headers.Authorization = 'Bearer x'; // mutates defaults.headers
console.log(defaults.retries); // 3
console.log(defaults.headers); // { Accept: 'application/json', Authorization: 'Bearer x' }Every later request now sends that token. A shallow copy does not fix it, because Object.assign and spread copy the headers reference and not the object it points to:
const defaults = { headers: { Accept: 'application/json' } };
const shallow = { ...defaults };
shallow.headers.X = '1';
console.log(defaults.headers.X); // '1'
const deep = structuredClone(defaults); // Node 17+, modern browsers
deep.headers.Y = '2';
console.log(defaults.headers.Y); // undefinedYou can also replace the nested object instead of mutating it, for example request.headers = { ...request.headers, Authorization: 'Bearer x' }. That is an assignment, so it creates an own property.
When Sharing Is Intended
Sometimes one value really should be shared, such as a lookup table of constants. In that case, make it impossible to mutate by accident with Object.freeze:
'use strict';
function Shape() {}
Shape.prototype.units = Object.freeze(['px', 'em', 'rem']);
const s = new Shape();
try {
s.units.push('vw');
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(Shape.prototype.units.length); // 3push on a frozen array throws a TypeError even outside strict mode. Assigning to a property of a frozen plain object fails silently in sloppy mode and throws only in strict mode. Object.freeze is also shallow, so nested objects need their own freeze.
Exercises
Exercise
An object proto is { scores: [], total: 0 }. You create p = Object.create(proto) and run p.total += 10; p.scores.push(10);. What are proto.total and proto.scores afterward, and why do the two lines behave differently?
Show answer
proto.total is still 0, and proto.scores is [10]. p.total += 10 reads 0 through the chain and then assigns 10 to p, which creates an own total. p.scores.push(10) only reads scores, gets the shared array from proto, and mutates it in place.
Exercise
A class is declared as class Logger { static lines = []; log(msg) { Logger.lines.push(msg); } }, and class FileLogger extends Logger {} is declared after it. After new FileLogger().log('a'), what is FileLogger.lines? Is this a bug?
Show answer
FileLogger.lines is ['a']. FileLogger has no own lines, so the lookup falls through to Logger (constructors inherit statics through their own prototype link), and both names refer to the same array. Whether that is a bug depends on intent. A single global log is fine. If each subclass needs its own list, declare static lines = [] in each subclass, or key the storage by this inside a static method.
Exercise
Rewrite function Queue() {} Queue.prototype.jobs = []; Queue.prototype.enqueue = function (j) { this.jobs.push(j); }; so that two queues never share jobs, while enqueue stays shared on the prototype.
Show answer
Move the array into the constructor: function Queue() { this.jobs = []; } Queue.prototype.enqueue = function (j) { this.jobs.push(j); };. Each new Queue() now gets its own jobs array, and enqueue stays one shared function on Queue.prototype.