Prototypal Inheritance
Prototypal Inheritance
Section titled “Prototypal Inheritance”Introduction
Section titled “Introduction”Before ES6 classes, JavaScript used constructor functions and manual prototype manipulation to implement inheritance. Understanding this pattern helps you understand how JavaScript’s inheritance actually works under the hood.
The Classical Pattern
Section titled “The Classical Pattern”// Parent constructorfunction Animal(name) { this.name = name;}
// Parent method on prototypeAnimal.prototype.eat = function() { return `${this.name} is eating`;};
// Child constructorfunction Dog(name, breed) { Animal.call(this, name); // Call parent constructor this.breed = breed;}
// Set up prototype chainDog.prototype = Object.create(Animal.prototype);Dog.prototype.constructor = Dog; // Fix constructor reference
// Add child methodsDog.prototype.bark = function() { return `${this.name} says woof!`;};
const rex = new Dog('Rex', 'Labrador');console.log(rex.eat()); // 'Rex is eating' — inheritedconsole.log(rex.bark()); // 'Rex says woof!' — ownStep by Step
Section titled “Step by Step”function Animal(name) { this.name = name; }Animal.prototype.eat = function() { return `${this.name} is eating`; };
function Dog(name, breed) { // Step 1: Call parent constructor to initialize name Animal.call(this, name); this.breed = breed;}
// Step 2: Set Dog.prototype to inherit from Animal.prototypeDog.prototype = Object.create(Animal.prototype);
// Step 3: Fix the constructor referenceDog.prototype.constructor = Dog;
// Step 4: Add Dog-specific methodsDog.prototype.bark = function() { return `${this.name} says woof!`; };Why Fix the Constructor?
Section titled “Why Fix the Constructor?”console.log(Dog.prototype.constructor); // Dog (after fix)// Without fix: Dog.prototype.constructor would be Animal
const rex = new Dog('Rex', 'Lab');console.log(rex.constructor); // Dog (because we fixed it)The instanceof Check
Section titled “The instanceof Check”const rex = new Dog('Rex', 'Lab');
console.log(rex instanceof Dog); // trueconsole.log(rex instanceof Animal); // true — inherits from Animalconsole.log(rex instanceof Object); // true — inherits from ObjectSummary
Section titled “Summary”- Constructor functions set up instance-specific properties
- Prototype methods are shared across instances
Object.create()sets up the prototype chain- Always fix the constructor reference
- The pattern works but is verbose — ES6 classes simplify it