Sub topic 11
The Prototype Chain and Inherited Properties
So far, every property you have read lived directly on the object you were using. That is only half of how JavaScript works. Most objects also have a hidden link to another object, called their prototype. When a property is missing on the object, the engine follows this link and looks there. This chapter explains how that lookup works, how writing differs from reading, and which common bugs come from inherited properties.
This chapter assumes you are comfortable with object literals, dot and bracket access, in versus Object.hasOwn, methods and this, and Object.keys and for...in from earlier chapters.
The hidden [[Prototype]] link
Every ordinary object has an internal slot that the specification calls [[Prototype]]. It holds either another object or null. You cannot reach this slot as a normal property. You read it with Object.getPrototypeOf and set it when you create the object, most directly with Object.create.
const animal = {
eats: true,
describe() {
return `${this.name} eats: ${this.eats}`;
}
};
const rabbit = Object.create(animal);
rabbit.name = "Rabbit";
console.log(rabbit.eats); // true (inherited)
console.log(rabbit.describe()); // "Rabbit eats: true"
console.log(Object.hasOwn(rabbit, "eats")); // false
console.log(Object.getPrototypeOf(rabbit) === animal); // true
console.log(Object.getPrototypeOf(animal) === Object.prototype); // true
console.log(Object.getPrototypeOf(Object.prototype)); // nullObject.create(animal) makes a new, empty object whose prototype is animal. rabbit has only one own property, name. It still answers rabbit.eats because the engine finds eats one step up the chain.
An object literal such as animal gets Object.prototype as its prototype automatically. Object.prototype is the end of the line, because its own prototype is null. The series of links, rabbit → animal → Object.prototype → null, is the prototype chain.
How a property read walks the chain
When you evaluate obj.key, the engine runs roughly this algorithm:
- If
objhas an own property namedkey, return its value. - Otherwise, take
obj's prototype. If it isnull, returnundefined. - Otherwise, repeat step 1 with the prototype in place of
obj.
The first match wins, so a property close to the object hides any property with the same name further up. This is why rabbit.toString() works even though neither rabbit nor animal defines toString: the search reaches Object.prototype.
this refers to the receiver, not the owner
rabbit.describe() found describe on animal, but inside it this.name printed "Rabbit". A method call binds this to the object before the dot, the receiver. Where the method was found in the chain does not matter. This lets one method on a prototype serve many objects, each with its own data.
Writes do not walk the chain
Reading searches the chain. Assignment normally does not. obj.key = value creates or updates an own property on obj, even if a property with that name exists on a prototype. The new own property shadows the inherited one.
const animal = { eats: true };
const rabbit = Object.create(animal);
rabbit.eats = false;
console.log(rabbit.eats); // false (own property)
console.log(animal.eats); // true (unchanged)
delete rabbit.eats;
console.log(rabbit.eats); // true (inherited again)delete also works only on own properties. Deleting rabbit.eats removes the shadow and exposes the inherited value again. delete rabbit.eats cannot remove animal.eats.
There are two exceptions to "assignment creates an own property". Both come from property attributes and accessors, which later chapters cover in detail:
- If the inherited property is an accessor with a setter, assignment calls that setter with
thisset to the receiver. No own property is created unless the setter creates one. - If the inherited property is a data property marked non-writable, assignment fails silently in sloppy mode and throws a
TypeErrorin strict mode.
The shared mutable value trap
Shadowing protects you only when you assign. Mutating an inherited object or array changes the one copy that every descendant shares.
const base = { tags: [] };
const a = Object.create(base);
const b = Object.create(base);
a.tags.push("x"); // reads a.tags (inherited), then mutates it
console.log(b.tags); // ["x"]
console.log(Object.hasOwn(a, "tags")); // false
a.tags = ["y"]; // assignment: creates an own property on a
console.log(b.tags); // ["x"]a.tags.push("x") is a read of tags followed by a method call, so no assignment to a ever happens. Keep per-object state as own properties. Put only shared behavior, usually methods, on the prototype.
Inherited properties in enumeration
The earlier chapter on enumeration showed that for...in and Object.keys differ. The prototype chain is the reason. for...in visits enumerable properties of the object and of every object on its chain, own properties first. Object.keys, Object.values, Object.entries, and spread syntax use only own enumerable properties.
const parent = { inherited: 1 };
const child = Object.create(parent);
child.own = 2;
for (const k in child) {
console.log(k); // "own", then "inherited"
}
console.log(Object.keys(child)); // ["own"]
console.log({ ...child }); // { own: 2 }The built-in methods on Object.prototype, such as toString, never show up in for...in because they are non-enumerable. Properties you add to a prototype yourself are enumerable by default, and they will show up. If you must use for...in, filter with Object.hasOwn(child, k). In most code, Object.keys or Object.entries is the simpler choice.
Where prototypes come from
You rarely call Object.create in application code. Most prototypes are set up for you.
| How the object is created | Its prototype |
|---|---|
| `{}` object literal | `Object.prototype` |
| `[]` array literal | `Array.prototype` |
| `Object.create(p)` | `p` |
| `Object.create(null)` | `null` (no prototype) |
| `new F()` with a function `F` | `F.prototype` |
| `new C()` with a class `C` | `C.prototype` |
| `{ __proto__: p }` literal | `p` |
Arrays are a good example of a longer chain. [1, 2].map is found on Array.prototype, and [1, 2].hasOwnProperty is found one step further, on Object.prototype.
Constructor functions and classes use the same mechanism. Each function has a prototype property, an ordinary object. new creates an object whose [[Prototype]] is that object.
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.length = function () {
return Math.hypot(this.x, this.y);
};
class Vec {
constructor(x, y) {
this.x = x;
this.y = y;
}
length() {
return Math.hypot(this.x, this.y);
}
}
const p = new Point(3, 4);
const v = new Vec(6, 8);
console.log(p.length()); // 5
console.log(v.length()); // 10
console.log(Object.getPrototypeOf(p) === Point.prototype); // true
console.log(Object.getPrototypeOf(v) === Vec.prototype); // true
console.log(Object.hasOwn(v, "length")); // falseChanging a prototype after creation
Object.setPrototypeOf(obj, p) changes the prototype of an existing object. The legacy obj.__proto__ accessor does the same. Both work, but engines optimize property access based on an object's shape and chain, and changing the chain afterward can slow down every later access to that object. Set the prototype when you create the object. The __proto__ key inside an object literal, as in { __proto__: p, x: 1 }, is standard syntax that does this at creation time and is fine to use.
Objects with no prototype
Because a plain {} inherits from Object.prototype, it already answers to names like constructor, toString, and hasOwnProperty. This breaks objects used as dictionaries with keys you do not control.
const words = ["apple", "constructor", "apple"];
const counts = {};
for (const w of words) {
counts[w] = (counts[w] || 0) + 1;
}
console.log(counts.apple); // 2
console.log(typeof counts.constructor); // "string": the inherited Object function was converted, then 1 appended
const safe = Object.create(null);
for (const w of words) {
safe[w] = (safe[w] || 0) + 1;
}
console.log(safe.apple); // 2
console.log(safe.constructor); // 1
console.log("toString" in safe); // falseIn the first loop, counts["constructor"] read the inherited Object function, which is truthy, so Object + 1 produced a string. An object made with Object.create(null) has an empty chain, so only keys you add exist. The cost is that it lacks every Object.prototype method: safe.hasOwnProperty is undefined, and converting it to a string throws a TypeError. Use Object.hasOwn(safe, key) instead of safe.hasOwnProperty(key). For dictionaries with arbitrary keys, a Map is often clearer still.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Changing one instance changes all of them | Mutable array or object stored on the prototype | Create per-instance state in the constructor or as own properties |
| `for...in` lists unexpected keys | Enumerable properties added to a prototype | Use `Object.keys`/`Object.entries`, or filter with `Object.hasOwn` |
| A lookup returns a function for an unexpected key | Dictionary key collides with an `Object.prototype` name | Use `Object.create(null)` or a `Map` |
| `obj.hasOwnProperty is not a function` | Object has a `null` prototype | Use `Object.hasOwn(obj, key)` |
| `delete obj.key` has no effect | `key` is inherited, not own | Delete from the object that owns it, or shadow it |
Exercise
Given const a = { x: 1 }; const b = Object.create(a); const c = Object.create(b); b.x = 2; delete c.x;, what do c.x, a.x, and Object.hasOwn(c, "x") evaluate to, and why?
Show answer
c.x is 2, a.x is 1, and Object.hasOwn(c, "x") is false. The assignment b.x = 2 created an own property on b that shadows a.x without changing it. delete c.x does nothing because c has no own x. Reading c.x walks up to b and finds 2 there first.
Exercise
A teammate writes function Cart() {} Cart.prototype.items = []; and then const c1 = new Cart(); const c2 = new Cart(); c1.items.push("book");. What is c2.items, and how should Cart be rewritten?
Show answer
c2.items is ["book"], because both instances inherit the same array from Cart.prototype and push mutates it without creating an own property. Move the state into the constructor: function Cart() { this.items = []; }, so each instance gets its own array. Methods can stay on the prototype.
Exercise
Write a function ownAndInherited(obj) that returns an object { own: [...], inherited: [...] } listing the enumerable string keys of obj, split by whether they are own properties.
Show answer
function ownAndInherited(obj) { const result = { own: [], inherited: [] }; for (const k in obj) { (Object.hasOwn(obj, k) ? result.own : result.inherited).push(k); } return result; }. For child from this chapter it returns { own: ["own"], inherited: ["inherited"] }, because for...in visits the enumerable keys along the whole chain and Object.hasOwn separates them.