Chapter XIX · Prototypes

Inheritance

Inheritance is the mechanism allowing one object or class to access and reuse properties and methods defined in another.

01 How It Works

Think of an industrial vehicle blueprint inheriting standard chassis engineering specs from a parent truck template.

JavaScript implements inheritance prototypally by linking object instances directly to parent prototype templates.

example.js
const animal = {
  speak() { console.log("Making sound"); }
};
const dog = Object.create(animal);
dog.speak(); // "Making sound"
  1. 1. Define a base parent object or constructor template.

  2. 2. Link a child object or constructor prototype to the base template.

  3. 3. Inherit shared behaviors cleanly.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
function Animal(name) { this.name = name; }
Animal.prototype.walk = function() { console.log(this.name + " walks"); };

function Dog(name) { Animal.call(this, name); }
Dog.prototype = Object.create(Animal.prototype);

Key Takeaway

Prototypal inheritance enables code reusability across object hierarchies in JavaScript.

Related Concepts