mediumJS ES5#57

Prototype chain lookup

Prompt

Create a Dog constructor that inherits from Animal via the prototype chain. Animal has a breathe method; Dog adds bark. A dog must be instanceof Animal, Animal.prototype must not gain bark, and Dog.prototype.constructor must be repaired.

Solution

function Animal() {}
Animal.prototype.breathe = function() { return 'breathing' }

function Dog() {}
Dog.prototype = Object.create(Animal.prototype)
Dog.prototype.constructor = Dog
Dog.prototype.bark = function() { return 'woof' }
Mentor's take

This is what class Dog extends Animal compiles down to, and the two lines after the constructor are where every candidate either proves or disproves prototype fluency. Object.create(Animal.prototype) builds a fresh object whose internal prototype link points at Animal.prototype — so lookup on a dog walks instance → Dog.prototypeAnimal.prototype, finding bark at the second hop and breathe at the third. That chain is also what instanceof traverses.

Why Object.create and not the two tempting alternatives? Dog.prototype = Animal.prototype doesn't inherit — it aliases: adding bark would stamp it onto Animal itself, giving every animal a bark (this file's tests catch exactly that pollution). Dog.prototype = new Animal() mostly works but runs the parent constructor at setup time — with real constructors that means executing side effects and baking parent instance state into the shared prototype. Object.create gives you the link and nothing else.

The constructor repair matters because replacing the prototype wholesale discarded the original object that carried constructor: Dog; without the fix, new Dog().constructor reports Animal through the chain — constructor is a writable convention, only as trustworthy as the last person who reassigned a prototype.

Red flag: Dog.prototype = Animal.prototype. It passes the happy-path test and corrupts the parent — the kind of bug that surfaces three features later.

Say it: "Object.create gives me the prototype link without running the parent constructor, then I repair constructor because wholesale prototype replacement clobbers it — that's the desugared version of extends."