Sub topic 13
Inheritance Before Classes: Linking Constructor Prototypes
This chapter assumes you already know how constructor functions and their prototype property work, what new does step by step, and what the constructor property is for. Here those pieces come together. You will build a parent-child relationship between two constructor functions by hand. This is the pattern that ES5 code used for years, and it is still what class and extends produce under the hood.
The Goal: Two Kinds of Sharing
An instance of a child "type" needs two things from its parent:
- The parent's per-instance setup. If
Animalsetsthis.name, then everyDogneeds its ownnametoo. - The parent's shared methods. If
Animal.prototype.speakexists, then aDogshould find it through the prototype chain.
Each need has its own fix. You get the per-instance setup by calling the parent constructor with the child's this. You get the shared methods by linking Dog.prototype to Animal.prototype. The usual bugs come from mixing these two up or doing only one of them.
The Canonical Pattern
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function () {
return `${this.name} makes a sound`;
};
function Dog(name) {
Animal.call(this, name); // run the parent constructor on this instance
}
Dog.prototype = Object.create(Animal.prototype);
Object.defineProperty(Dog.prototype, 'constructor', {
value: Dog,
writable: true,
configurable: true,
enumerable: false
});
Dog.prototype.speak = function () {
return `${Animal.prototype.speak.call(this)}, woof`;
};
const rex = new Dog('Rex');
console.log(rex.speak()); // "Rex makes a sound, woof"
console.log(rex instanceof Animal); // true
console.log(rex.constructor === Dog); // trueThe steps:
Animal.call(this, name)runsAnimal's body withthisset to the newDoginstance. Because of this,namebecomes an own property ofrex.Object.create(Animal.prototype)makes a new, empty object whose[[Prototype]]isAnimal.prototype. That object replaces the defaultDog.prototype.Animalitself does not run here.Object.defineProperty(... 'constructor' ...)puts back theconstructorproperty. You lost it when you replacedDog.prototype. UsingdefinePropertykeeps it non-enumerable, the same as the original, sofor...inloops over instances do not list it.Animal.prototype.speak.call(this)is the manual version ofsuper.speak(). You name the parent's method directly and call it with the currentthis.
Here is what happens when you look up rex.speak. The engine checks rex and finds nothing. It then checks Dog.prototype and finds the override there. A lookup for rex.hasOwnProperty goes two steps further, all the way to Object.prototype.
Order Matters: Link First, Then Add Methods
Assigning Dog.prototype = Object.create(...) throws away the old prototype object, and every method on it goes with it. If you add methods before you relink, they disappear without any error:
function Animal() {}
function Dog() {}
Dog.prototype.fetch = function () { return 'fetching'; };
Dog.prototype = Object.create(Animal.prototype); // fetch is gone
console.log(typeof new Dog().fetch); // "undefined"Always relink first. Add methods after.
Common Mistakes
Mistake 1: Sharing the Parent's Prototype Object
function Animal(name) { this.name = name; }
Animal.prototype.speak = function () { return `${this.name} makes a sound`; };
function Cat(name) { Animal.call(this, name); }
Cat.prototype = Animal.prototype; // same object, not a link
Cat.prototype.speak = function () { return `${this.name} meows`; };
console.log(new Animal('Generic').speak()); // "Generic meows"Cat.prototype and Animal.prototype are now the same object. When you "override" a method on Cat, you overwrite it for every animal. Object.create exists to give you a separate object that only delegates to the parent.
Mistake 2: Using `new Parent()` as the Child Prototype
Older tutorials often write Dog.prototype = new Animal(). This does link the chain. It also runs the parent constructor once, with no real arguments, and stores its instance state on the shared prototype:
function Animal(name) {
this.name = name;
this.tricks = [];
}
function BadDog() {} // forgot Animal.call(this, ...)
BadDog.prototype = new Animal('generic');
const a = new BadDog();
const b = new BadDog();
a.tricks.push('sit');
console.log(a.name); // "generic"
console.log(b.tricks); // ['sit']Every BadDog inherits the same tricks array. This is the shared-mutable-state pitfall caused by a constructor call. The problem gets worse if Animal has side effects or checks its arguments, because that code runs while you are only defining the type.
Mistake 3: Forgetting `Parent.call(this, ...)`
If you link the prototypes but never call the parent constructor, then methods are inherited but the state they depend on is missing. speak() returns "undefined makes a sound".
Mistake 4: Forgetting to Restore `constructor`
If you skip the defineProperty step, rex.constructor finds Animal.prototype.constructor and returns Animal. instanceof still works, because it walks the prototype chain and does not read constructor. Code that does new obj.constructor(...) to clone an instance will quietly build the wrong type.
| Approach | Chain linked? | Parent runs at definition? | Separate child prototype? |
|---|---|---|---|
| `Child.prototype = Parent.prototype` | No extra level | No | No (shared) |
| `Child.prototype = new Parent()` | Yes | Yes | Yes, but holds instance state |
| `Child.prototype = Object.create(Parent.prototype)` | Yes | No | Yes |
| `Object.setPrototypeOf(Child.prototype, Parent.prototype)` | Yes | No | Yes, keeps original object |
An Alternative: Relink Without Replacing
Object.setPrototypeOf(Dog.prototype, Animal.prototype) changes the existing prototype's link and does not replace the object. This keeps the original constructor property and any methods already defined. The trade-off is that it changes a prototype after the object exists, which engines optimize less well. Doing it once at definition time, before any instances exist, costs little in practice.
What This Pattern Does Not Do
The hand-built version links the instances' chain only. The constructors themselves are not linked:
function Animal() {}
Animal.create = function () { return new this(); };
function Dog() { Animal.call(this); }
Dog.prototype = Object.create(Animal.prototype);
console.log(Object.getPrototypeOf(Dog) === Function.prototype); // true
console.log(typeof Dog.create); // "undefined"Static helpers do not pass down unless you also call Object.setPrototypeOf(Dog, Animal). Class syntax does this for you, which is one of several gaps that extends closes.
Exercise
In the canonical Dog/Animal example, suppose you delete the Object.defineProperty call. What do rex.constructor and rex instanceof Dog evaluate to, and why?
Show answer
rex.constructor is Animal. The fresh object from Object.create has no own constructor, so the lookup continues to Animal.prototype.constructor. rex instanceof Dog is still true, because instanceof checks whether Dog.prototype appears in rex's prototype chain, and it does.
Exercise
Why is Dog.prototype = Object.create(Animal.prototype) preferred over Dog.prototype = new Animal()?
Show answer
Object.create links Dog.prototype to Animal.prototype without running Animal. new Animal() runs the constructor at definition time, with meaningless arguments and any side effects, and leaves per-instance properties (such as a tricks array) on the shared prototype, where every Dog inherits them.
Exercise
Write a Puppy constructor that inherits from Dog (defined above), adds an own property age, and overrides speak to append " (puppy)" to Dog's result.
Show answer
function Puppy(name, age) { Dog.call(this, name); this.age = age; } Puppy.prototype = Object.create(Dog.prototype); Object.defineProperty(Puppy.prototype, 'constructor', { value: Puppy, writable: true, configurable: true, enumerable: false }); Puppy.prototype.speak = function () { return ${Dog.prototype.speak.call(this)} (puppy); }; new Puppy('Bit', 1).speak() returns "Bit makes a sound, woof (puppy)".