JavaScriptFundamental (ES6), part 1
Build a prototype chain with Object.create in JavaScript
143 a prototype chain built by hand, and what instanceof reads
hardBuild a chain with Object.create instead of class, walk it with Object.getPrototypeOf, and show that writing an inherited property shadows it rather than changing the parent. Then take instanceof apart: make it say true for an object no constructor ever touched, make it say false for a genuine instance, override it completely with Symbol.hasInstance, and find the object it cannot answer for at all.
Stuck? Three hints, smallest first
- 1.
Object.create(proto)makes an empty object whose prototype isproto. Nothing is copied. - 2.
a instanceof Basks one question: isB.prototypeanywhere ona’s prototype chain? It never looks at howawas made. - 3. So reassigning
B.prototypeafter making an instance leaves that instance pointing at an object no longer named byB.
const vehicle = {
wheels: 4,
describe() { return this.kind + ' on ' + this.wheels + ' wheels'; },
};
const danfo = Object.create(vehicle);
danfo.kind = 'danfo';
const okada = Object.create(vehicle, {
kind: { value: 'okada', enumerable: true, writable: true },
wheels: { value: 2, enumerable: true, writable: true },
});
const asBuilt = [danfo.describe(), okada.describe()];
const nameOf = (o) =>
o === danfo ? 'danfo' : o === vehicle ? 'vehicle' : o === Object.prototype ? 'Object.prototype' : 'other';
const walk = [];
let cursor = danfo;
while (cursor !== null) { walk.push(nameOf(cursor)); cursor = Object.getPrototypeOf(cursor); }
const ownBefore = Object.keys(danfo);
const inherited = [danfo.wheels, Object.hasOwn(danfo, 'wheels')];
danfo.wheels = 6; // creates an OWN property
const afterWrite = [danfo.wheels, vehicle.wheels, okada.wheels, Object.hasOwn(danfo, 'wheels')];
function Vehicle() {}
Vehicle.prototype = vehicle; // instanceof reads the RIGHT side's .prototype
const neverConstructed = danfo instanceof Vehicle;
function Bus() {}
const firstBus = new Bus();
Bus.prototype = { rows: 10 }; // a different object entirely
const secondBus = new Bus();
const orphaned = [firstBus instanceof Bus, secondBus instanceof Bus];
class Wheeled {
static [Symbol.hasInstance](value) { return typeof value?.wheels === 'number'; }
}
const hijacked = [{ wheels: 3 } instanceof Wheeled, { wheels: 'plenty' } instanceof Wheeled];
const bare = Object.create(null);
bare.kind = 'bare';
const bareFacts = [typeof bare.toString, 'toString' in bare, Object.getPrototypeOf(bare), bare instanceof Object];
const fromTheOtherEnd = [vehicle.isPrototypeOf(danfo), Object.prototype.isPrototypeOf(bare)];
console.log('as built :', asBuilt);
console.log('chain :', walk, '| own keys:', ownBefore);
console.log('shadowing :', inherited, '->', afterWrite);
console.log('instanceof:', neverConstructed, orphaned, hijacked);
console.log('no chain :', bareFacts, '| isPrototypeOf:', fromTheOtherEnd);
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 method reads the child own data, and a defineProperty override wins', asBuilt, ['danfo on 4 wheels', 'okada on 2 wheels']);
test('the chain is exactly the objects you linked, ending at null', walk, ['danfo', 'vehicle', 'Object.prototype']);
test('an inherited property is readable but not owned', [ownBefore, inherited], [['kind'], [4, false]]);
test('writing it creates an own property and leaves every sibling alone', afterWrite, [6, 4, 2, true]);
test('instanceof is true for an object no constructor ever touched', neverConstructed, true);
test('and false for a real instance, once .prototype has been reassigned', orphaned, [false, true]);
test('Symbol.hasInstance replaces the walk with whatever you like', hijacked, [true, false]);
test('Object.create(null) has no chain, so it is not even an instanceof Object', bareFacts, ['undefined', false, null, false]);
test('isPrototypeOf asks the same question from the other end', fromTheOtherEnd, [true, false]);
There is only one inheritance mechanism in JavaScript, and it is this: every object has a hidden link to another object, and a failed property lookup follows the link. class, new and Object.create are three spellings for wiring that link. Reading walks the chain; writing never does. danfo.wheels = 6 installs an own property that shadows the parent, which is why one instance changing a value cannot corrupt its siblings, and also why a shared mutable default on a prototype is a bug waiting for its first push.
instanceof is far dumber than its name suggests. It takes the object on the right, reads its .prototype property, and looks for that exact object on the left operand chain. It does not record what constructed anything. So pointing Vehicle.prototype at an object already in danfo chain makes danfo instanceof Vehicle true with no constructor call, and swapping Bus.prototype for a fresh object makes an object built by new Bus() stop being a Bus. The same reasoning is why instanceof fails across iframes and across two copies of a library: same class, two .prototype objects.
Two escape hatches follow. Symbol.hasInstance lets the right-hand side answer for itself, which is duck typing with the operator syntax. And Object.create(null) produces an object with no chain at all: no toString, no hasOwnProperty, and instanceof Object is false. That is exactly what you want for a lookup table keyed by untrusted strings, since there is no inherited __proto__ or constructor to collide with. Reach for Object.hasOwn and Object.getPrototypeOf rather than the methods such an object does not have.