Sub topic 2
Walking the Prototype Chain
This chapter assumes you can write object literals, call methods, and run JavaScript in Node.js or a browser console. It also builds on the previous chapter's idea that every object has a hidden [[Prototype]] link.
Lookup Follows the Links
When you read a property such as obj.x, JavaScript runs a search:
- Check whether
objhas an own property namedx. If it does, return that value. - If not, follow
obj's[[Prototype]]link to the next object and check there. - Repeat until the property is found or the link is
null. - If the search reaches
null, the result isundefined.
The objects visited this way form the prototype chain. For ordinary objects, the last stop is Object.prototype, whose own prototype is null. That is why every plain object can call toString even though you never defined it.
Seeing It in Code
The example below uses Object.create(proto), which makes a new object whose prototype is proto. A later chapter covers it in detail.
const grandparent = {
greet() {
return 'hello';
}
};
const parent = Object.create(grandparent);
parent.role = 'parent';
const child = Object.create(parent);
child.name = 'Kid';
console.log(child.name); // "Kid" (own property)
console.log(child.role); // "parent" (found one link up)
console.log(child.greet()); // "hello" (found two links up)
console.log(child.toString()); // "[object Object]" (from Object.prototype)
console.log(child.missing); // undefined (search reached null)
function chainOf(obj) {
const links = [];
let current = Object.getPrototypeOf(obj);
while (current !== null) {
links.push(current);
current = Object.getPrototypeOf(current);
}
return links;
}
const links = chainOf(child);
console.log(links.length); // 3
console.log(links[0] === parent); // true
console.log(links[2] === Object.prototype); // trueThe search stops at the first match. If child and grandparent both had a greet, the one on child would win, and the search would never reach grandparent.
Where the Chain Stops
The chain has to end, and the engine enforces this. If you try to create a loop, JavaScript throws an error:
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
}Common Errors
| Mistake | What actually happens |
|---|---|
| Treating `undefined` as proof the property doesn't exist | The property may exist with the value `undefined`. Check for existence explicitly. |
| Expecting writes to walk the chain | Reads walk the chain. Assignment usually creates an own property, as the shadowing chapter explains. |
| Assuming a method lives on the object | It may be inherited from several links up. Edits to that ancestor affect every object below it. |
| Building very deep chains | Each missing property makes the engine check every link. Deep chains are also hard to reason about. |
Exercise
Given const base = { kind: 'base' }; const mid = Object.create(base); const top = Object.create(mid); mid.kind = 'mid';, what does top.kind return, and how many objects does the lookup check?
Show answer
It returns "mid". The lookup checks top, where it finds no own kind, then mid, where it finds kind. That is two objects. It stops at mid and never reaches base.
Exercise
Why does ({}).hasOwnProperty('x') work even though the empty object has no own properties?
Show answer
Lookup for hasOwnProperty fails on the empty object, follows its [[Prototype]] link to Object.prototype, and finds the method there. The method then runs with this set to the empty object.