Sub topic 3
Walking the Prototype Chain
This chapter assumes you know object literals, property access with dot and bracket notation, and how this is bound in a method call. It builds on the previous chapter: every object has a hidden [[Prototype]] link that points to another object or to null. Here you follow those links one after another and see how JavaScript uses them to find properties.
The Lookup Algorithm
When you read obj.key, the engine runs a short loop:
- Look for an own property named
keyonobj. If it is there, use it and stop. - If not, follow
obj's[[Prototype]]link to the next object. - Repeat step 1 on that object.
- If the link is
null, stop and returnundefined.
The objects visited in this loop form the prototype chain. The search stops at the first match, so an object near the front of the chain takes priority over objects behind it.
A Three-Level Chain
The example below builds a chain with Object.create, which makes a new object whose prototype is the argument. The next chapter covers Object.create in detail. For now, read Object.create(x) as "a new empty object linked to x".
const base = {
level: 'base',
greet() {
return 'hello';
}
};
const middle = Object.create(base);
middle.level = 'middle';
middle.middleOnly = true;
const leaf = Object.create(middle);
leaf.own = 1;
console.log(leaf.own); // 1 (found on leaf)
console.log(leaf.middleOnly); // true (found on middle)
console.log(leaf.level); // "middle" (middle wins; base is never checked)
console.log(leaf.greet()); // "hello" (found on base)
console.log(leaf.toString); // [Function: toString] (found on Object.prototype)
console.log(leaf.missing); // undefined (chain exhausted)leaf.toString resolves even though none of our objects define it. base was written as an object literal, and object literals are linked to Object.prototype. So the full chain is:
Listing a Chain in Code
Object.getPrototypeOf(obj) returns the object that obj's [[Prototype]] points to. A later chapter covers it fully. With it you can print any chain:
function chainOf(obj) {
const links = [];
let current = obj;
while (current !== null) {
links.push(current);
current = Object.getPrototypeOf(current);
}
return links;
}
const arr = [1, 2, 3];
const chain = chainOf(arr);
console.log(chain.length); // 3
console.log(chain[1] === Array.prototype); // true
console.log(chain[2] === Object.prototype); // true
console.log(Object.getPrototypeOf(Object.prototype)); // nullBuilt-in values use the same mechanism. Arrays find map and push on Array.prototype, and functions find call and bind on Function.prototype. Both chains continue to Object.prototype and end at null.
Reimplementing Lookup
Writing the algorithm yourself makes its rules concrete. This version handles data properties and getters:
function lookup(obj, key) {
let current = obj;
while (current !== null) {
const desc = Object.getOwnPropertyDescriptor(current, key);
if (desc !== undefined) {
if ('value' in desc) return desc.value;
return desc.get ? desc.get.call(obj) : undefined;
}
current = Object.getPrototypeOf(current);
}
return undefined;
}
const shape = {
get description() {
return `${this.name} with ${this.sides} sides`;
}
};
const square = Object.create(shape);
square.name = 'square';
square.sides = 4;
console.log(lookup(square, 'description')); // "square with 4 sides"
console.log(square.description); // "square with 4 sides"
console.log(lookup(square, 'nothing')); // undefinedNotice desc.get.call(obj). The getter is found on shape, but it runs with the original object as this. The object where a property is found and the object it acts on are separate, and this is what makes inherited methods useful. A later chapter covers this in inherited methods.
Edge Cases
A property set to undefined still stops the search
Lookup asks whether the property exists. It does not ask whether the value is useful:
const parent = { color: 'red' };
const child = Object.create(parent);
child.color = undefined;
console.log(child.color); // undefined (parent's 'red' is hidden)
console.log('color' in child); // trueIf obj.x === undefined, that does not tell you whether x is missing or whether it exists with the value undefined. Use in or Object.hasOwn when the difference matters. The chapter on own versus inherited properties compares them.
Chains cannot loop
If chains could form cycles, the lookup loop would never end. The engine refuses to create one:
const a = {};
const b = Object.create(a);
try {
Object.setPrototypeOf(a, b); // would make a -> b -> a
} catch (err) {
console.log(err instanceof TypeError); // true
}Primitives borrow a chain
'abc'.toUpperCase() works even though strings are not objects. The engine wraps the primitive in a temporary String object for the lookup, so the method is found on String.prototype. Numbers and booleans do the same with Number.prototype and Boolean.prototype. null and undefined have no wrapper, so null.x throws a TypeError instead of returning undefined.
Reading walks the chain; writing usually does not
Everything in this chapter is about reading. Plain assignment such as leaf.level = 'leaf' does not change middle or base. It creates an own property on leaf. Setters and non-writable inherited properties are exceptions, and the shadowing chapter covers them.
Common Errors
| Mistake | What actually happens |
|---|---|
| Expecting `obj.x === undefined` to mean `x` is absent | `x` may exist with the value `undefined`, or exist further up the chain |
| Assuming lookup checks every level and merges results | Lookup returns the first match only |
| Thinking a method's `this` is the object it was found on | `this` is the object you accessed the property through |
| Calling a method on `null` or `undefined` | Throws `TypeError`, because neither has a prototype chain |
| Building very long chains for code reuse | Each miss walks every level, and deep chains are hard to reason about |
Exercises
Exercise
Given const a = { x: 1, y: 2 }; const b = Object.create(a); b.y = 3; const c = Object.create(b); what do c.x, c.y, and c.z evaluate to, and on which object is each one found?
Show answer
c.x is 1, found on a. c.y is 3, found on b, and the search stops there, so a.y is never checked. c.z is undefined: the lookup checks c, b, a, and Object.prototype, then reaches null.
Exercise
Write a function depth(obj) that returns how many [[Prototype]] links you follow from obj before reaching null. What do depth({}), depth([]), and depth(Object.create(null)) return?
Show answer
function depth(obj) { let n = 0; let p = Object.getPrototypeOf(obj); while (p !== null) { n++; p = Object.getPrototypeOf(p); } return n; } It returns 1 for {} (Object.prototype), 2 for [] (Array.prototype, then Object.prototype), and 0 for Object.create(null).
Exercise
An inherited getter on proto returns this.id. If item = Object.create(proto) and item.id = 7, what does item.value (the getter) return, and why?
Show answer
It returns 7. The getter is found on proto, but lookup calls it with the original receiver, item, as this, so this.id reads item's own id.