Object-Oriented Design – Practical Differences Between Prototypal and Classical Inheritance

designinheritanceobject-oriented-design

Inheritance, Polymorphism, and Encapsulation are the three most distinct, important features of OOP, and from them, inheritance has a high usage statistics these days.
I'm learning JavaScript, and here, they all say that it has prototypal inheritance, and people everywhere say that it's something far different from classical inheritance.

However, I can't understand what's their difference from the point of practical usage? In other words, when you define a base class (prototype) and then derive some subclasses from it, you both have access to functionalites of your base class, and you can augment functions on the derived classes. If we consider what I said to be the intended result of inheritance, then why should we care if we're using prototypal or classic version?

To clear myself more, I see no difference in the usefulness and usage patterns of prototypal and classic inheritance. This results in me having no interest to learn why they are different, as they both result in the same thing, OOAD. How practically (not theoretically) prototypal inheritance is different from classical inheritance?

Best Answer

Recent blog post about JS OO

I believe what your comparing is classical OO emulation in JavaScript and classical OO and of course you can't see any difference.

Disclaimer: replace all references to "prototypal OO" with "prototypal OO in JavaScript". I don't know the specifics of Self or any other implementation.

However prototypal OO is different. With prototypes you only have objects and you can only inject objects into other objects prototype chain. Whenever you access a property on an object you search that object and any objects in the prototype chain.

For prototypal OO there is no notion of encapsulation. Encapsulation is a feature of scope, closures and first class functions but has nothing to do with prototypal OO. There is also no notion of inheritance, what people call "inheritance" is actually just polymorphism.

It does however have polymorphism.

For example

var Dog = {
  walk: function() { console.log("walks"); }
}

var d = Object.create(Dog);
d.walk();

Clearly d has access to the method Dog.walk and this exhibits polymorphism.

So actually there is a big difference. You only have polymorphism.

However as mentioned, if you desired to do so (I have no idea why you would) you can emulate classical OO in JavaScript and have access to (restricted) encapsulation and inheritance.

Related Topic