How does prototypal inheritance differ from classical inheritance?

Expert-Level Explanation

In JavaScript, prototypal inheritance is a mechanism by which objects can inherit properties and methods from other objects. This is different from classical inheritance, commonly found in languages like Java or C++, where classes inherit from other classes.

The key differences are:

  1. Nature of Inheritance: In classical inheritance, inheritance is a relationship between two classes (blueprints), whereas in prototypal inheritance, it's between two objects.

  2. Class vs. prototype: Classical inheritance uses 'classes' as blueprints to create objects. Prototypal inheritance, however, uses a 'prototype' object as a template from which other objects directly inherit.

  3. Inheritance Mechanism: Classical inheritance involves creating a hierarchy of classes through 'extends' and 'super' keywords. Prototypal inheritance is about objects delegating to other objects using JavaScript's internal [[Prototype]] chain.

  4. Flexibility: Prototypal inheritance can be more dynamic and flexible. Objects can inherit from other objects on the fly, and the prototype chain can be altered or extended at runtime.

Creative Explanation

Imagine classical inheritance as manufacturing cars using a fixed blueprint (class). Each car (or object) is made from this blueprint, and any changes to the design require altering the blueprint.

Prototypal inheritance is like sculpting clay models (objects). You can start with a basic shape (a prototype object) and modify it to create a new object. You can even press a new model against an existing one to copy its features directly.

Practical Explanation with Code

Classical inheritance (in languages like Java):

class Animal {
    void makeSound() {
        System.out.println("Some sound");
    }
}

class Dog extends Animal {
    void makeSound() {
        System.out.println("Bark");
    }
}

Prototypal Inheritance (in JavaScript):

const animal = {
    makeSound: function() {
        console.log("Some sound");
    }
};

const dog = Object.create(animal);
dog.makeSound = function() {
    console.log("Bark");
};

Real-world Example

Classical inheritance is like a family tree where traits (properties and methods) are passed down from generation to generation (class to class).

Prototypal inheritance is like a mentorship programme. A mentor (prototype object) can teach a mentee (new object), and the mentee can further develop those skills or even learn from multiple mentors (multiple prototypes).

Did you find this article valuable?

Support InterviewPro: Master Tech Fundamentals by becoming a sponsor. Any amount is appreciated!