JavaScriptFundamental (ES6), part 2
Prototype chain and property shadowing in JavaScript
76 The prototype chain, and what shadowing really does
fairBuild a two-link chain with Object.create. Read an inherited property, then assign to the same name and work out where the value landed. Delete it again. Compare Object.keys with for...in, walk the chain to its end, and see what an object with no prototype cannot do.
Stuck? Three hints, smallest first
- 1. A read walks up the chain. A write always lands on the object you wrote to.
- 2.
Object.hasOwnandindisagree about exactly the inherited properties. - 3.
Object.create(null)has notoString, so converting it to a string throws.
const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };
const vehicle = {
wheels: 4,
describe() { return this.name + ' with ' + this.wheels + ' wheels'; },
};
const danfo = Object.create(vehicle);
danfo.name = 'danfo';
const inherited = [danfo.wheels, Object.hasOwn(danfo, 'wheels'), 'wheels' in danfo];
const methodRuns = danfo.describe();
danfo.wheels = 6; // shadows; the prototype is untouched
const afterShadowing = [danfo.wheels, vehicle.wheels, Object.hasOwn(danfo, 'wheels')];
const shadowedDescribe = danfo.describe();
delete danfo.wheels; // the shadow goes, the inherited value returns
const afterDelete = [danfo.wheels, Object.hasOwn(danfo, 'wheels')];
const ownOnly = Object.keys(danfo);
const walked = [];
for (const key in danfo) walked.push(key);
const links = [Object.getPrototypeOf(danfo) === vehicle, vehicle.isPrototypeOf(danfo)];
const chain = [];
for (let link = Object.getPrototypeOf(danfo); link !== null; link = Object.getPrototypeOf(link)) {
chain.push(link === vehicle ? 'vehicle' : link === Object.prototype ? 'Object.prototype' : 'other');
}
const bare = Object.create(null);
bare.name = 'keko';
const bareChecks = [Object.getPrototypeOf(bare), 'toString' in bare, Object.keys(bare)];
const bareThrows = attemptName(() => String(bare));
console.log('inherited :', inherited);
console.log('after shadowing:', afterShadowing);
console.log('after delete :', afterDelete);
console.log('chain :', chain);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('an inherited property reads as if it were the object\'s own, but is not', inherited, [4, false, true]);
test('an inherited method runs with this as the object it was called on', methodRuns, 'danfo with 4 wheels');
test('assigning creates an own property and leaves the prototype alone', afterShadowing, [6, 4, true]);
test('so the inherited method now reads the shadowing value', shadowedDescribe, 'danfo with 6 wheels');
test('deleting the shadow uncovers the inherited value again', afterDelete, [4, false]);
test('Object.keys is own keys only, while for...in walks the chain', [ownOnly, walked], [['name'], ['name', 'wheels', 'describe']]);
test('the link is readable from both ends, and the chain ends at Object.prototype', [links, chain], [[true, true], ['vehicle', 'Object.prototype']]);
test('Object.create(null) has no chain, so no toString to inherit', bareChecks, [null, false, ['name']]);
test('which makes even String() on it a TypeError', bareThrows, 'TypeError');
The asymmetry is the whole subject: reads walk up the chain, writes never do. danfo.wheels = 6 does not modify vehicle and does not "override" anything — it creates an own property that the lookup finds first. That is why delete appears to restore a value it never touched, and why one shared prototype can safely back a thousand objects.
The trap sits one level down from here. Shadowing works cleanly for primitives, and hides a real problem for objects: if the prototype holds { tags: [] }, then obj.tags.push('x') is a read followed by a mutation, so every object sharing that prototype sees the push. Only an assignment shadows. That is the shared-state bug behind "why did adding a tag to one order add it to all of them".
for...in walking the chain is a leftover that still causes trouble: it lists inherited enumerable keys, which here means the method. That is why for...in over data needs Object.hasOwn guarding it, why class methods are non-enumerable by default — exercise 78 — and why Object.keys or Object.entries is what you actually want.
Object.create(null) is the deliberate opt-out, and the eighth and ninth assertions show both sides of it. No toString, no hasOwnProperty, no __proto__ accessor — which is precisely what you want from a lookup table keyed by user input, since a key called "toString" or "__proto__" is then just a key. The price is that the object cannot be logged, concatenated or compared as a string without throwing.