prototypal inheritance concept in javascript as a prototype based language

Classical inheritance is about extending types of things. Say you have a class, like Bike. When you want extend the behaviour, you have to design a new type of bike (like MotorBike).

It’s like building a factory – you make lots of blueprints, and blueprints that reference those blueprints, but in order to ride one you have to take the blueprint and make something from it.

Prototype-based inheritance is about extending things themselves. Say you have a way of making Bike objects. You take one of these Bikes into your garage, and you strap a jet engine to it.

This is not according to the blueprint. This is something you’ve done to this particular bike. But your friends see your contraption and want one too. So instead of making a blueprint for your new design, you stick up a sign saying “JetBike factory” and just start making more of them. And every time you can’t remember how something fits together, instead of looking at a blueprint you just look at your original bike. Your original bike is the prototype bike, and all the new bikes are based on it.

Now, for a genuine 6-year-old, that’s probably where I’d stop (if I hadn’t lost them already), but in reality prototype-based inheritance doesn’t just construct copies, it does something even cooler – it actually links the new JetBike objects to the original prototype bike you have in your garage. If you replace the suspension on your prototype bike, then all your friends’ bikes will also magically have their suspension replaced as well.

Let’s look at some JS-ish pseudo-code:

function Bike() {
    this.wheels = 2;
}
Bike.prototype = {
    ride: function() {
        // Ride the bike
    },
    crash: function() {
        // Fall off the bike
    }
};

function JetBike() {
    this.engines = 2;
}
// Start with an ordinary bike
JetBike.prototype = new Bike();
// Modify it
JetBike.prototype.fly = function () {
    // Engage thrusters and head for the ramp
};

Leave a Comment