Understanding Prototypical Inheritance

Prototypical inheritance is probably one of the most confusing subjects for my students. It’s a fundamental difference between Javascript and other modern languages, such as Ruby, and a lot of developers have trouble wrapping their heads around it.

Class-based Inheritance and the “is-a” relationship

Traditional languages such as Java, Ruby, and C++ use a concept called class-based inheritance. To demonstrate this, I’ll use the classic example of an Animal and a Dog.

Using classical inheritance, Dog and Animal can be said to have an “is-a” relationship (ie: A Dog IS-A Animal). When a new instance of a Dog is created, the properties of Animal are also included in the properties of Dog.

Since a Dog “Is-A” animal, calling the method getSpecies() on the Dog class works. The method was automatically added to the “Dog” class by the inheritance system.

Prototypical Inheritance and the Has-A Relationship

Javascript uses a concept called prototypical inheritance (although I hesitate to even call it inheritance). Using the “dog” and “animal” example above, we would say that, in a prototypical language, a dog HAS-A animal contained within it. This is an important distinction: In Javascript, a “subclass” contains an instance of it’s “superclass” in a special property called “prototype”.

In the example above, the “Dog” and “Animal” functions are completely separate from each other. The “Dog” object has a property called “prototype” which is set to an instance of a new Animal. Until the “prototype” property is set, there is no “inheritance” relationship.

When a method is called on an instance of the “dog” object, Javascript first checks the dog object to see if the method exists in dog. If it doesn’t, Javascript then goes into the “Animal” object contained within the “Dog” and checks to see if the method exists there. If it doesn’t, Javascript will continue to the prototype of the “Animal” class and so on, until it finds the method or runs out of prototypes.

This distinction between “is-a” and “has-a” is a critical difference between classical inheritance and prototypical inheritance. Keeping this difference in mind will make your Javascript life much easier.

Written by

Entrepreneur. Engineer. Educator.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store