Sub topic 11
Pitfall: Shared Mutable State on Prototypes
This chapter assumes you already know how shadowing works: assigning to a property creates an own property on the object. It also assumes you know that new links each instance to the constructor's prototype object. The trap described here comes from those two rules working together.
The working model
A prototype is one object, and every object linked to it shares it. Methods are safe to share because you call them and never change them. Data properties behave differently depending on their value:
- Primitives such as numbers, strings, and booleans can't be changed in place. To change one, you have to assign to it, and the assignment shadows the inherited value on that one object.
- Objects and arrays can be changed in place. Calling
push, setting a key, or modifying a nested field is a property read followed by a mutation. Nothing is assigned to the instance, so the shared object on the prototype changes.
const proto = { count: 0, tags: [] };
const a = Object.create(proto);
const b = Object.create(proto);
a.count = 5; // assignment: creates an own property on a
console.log(proto.count); // 0
console.log(b.count); // 0
a.tags.push('x'); // read a.tags (found on proto), then mutate it
console.log(b.tags); // ['x']
console.log(Object.hasOwn(a, 'tags')); // falseHow it shows up with constructors
The same bug appears when someone puts default data on Constructor.prototype to "set defaults once":
function Cart() {}
Cart.prototype.items = [];
const c1 = new Cart();
const c2 = new Cart();
c1.items.push('apple');
console.log(c2.items); // ['apple']: every cart shares one listThe fix: per-instance state in the constructor
Create mutable state inside the constructor, where this refers to the new instance. Keep only methods, and constants that never change, on the prototype.
function Cart() {
this.items = []; // a fresh array for each instance
}
Cart.prototype.add = function (item) {
this.items.push(item);
return this;
};
const c1 = new Cart().add('apple');
const c2 = new Cart();
console.log(c1.items); // ['apple']
console.log(c2.items); // []With class syntax, a class field does the same job. Its initializer runs once for each instance:
class Cart {
items = [];
add(item) {
this.items.push(item);
return this;
}
}
console.log(new Cart().add('pear').items); // ['pear']
console.log(new Cart().items); // []Common errors
| Symptom | Cause | Fix |
|---|---|---|
| A change on one instance appears on all of them | Mutable value stored on the prototype | Initialize it in the constructor or in a class field |
| `Object.hasOwn(obj, 'list')` is `false` after `push` | `push` mutates and never assigns | Give each instance its own value |
| Writing `obj.list = [...obj.list, x]` "fixes" it | The assignment shadows the shared array | Works, but initialize per instance to make the intent clear |
Exercise
Given function Team() {} Team.prototype.members = [];, what does new Team().members.length print after running const t = new Team(); t.members.push('Ada');, and how would you fix it?
Show answer
It prints 1. The push mutated the single array on Team.prototype, so every new Team sees it. To fix it, move the array into the constructor (function Team() { this.members = []; }) or use a class field (members = [];).
Exercise
Why does a.count = 5 leave b.count unchanged while a.tags.push('x') changes b.tags?
Show answer
a.count = 5 is an assignment, so it creates an own property on a that shadows the prototype's value. a.tags.push('x') only reads tags, finds it on the shared prototype, and mutates that one array in place.