Understanding Prototypal Inheritance

Inheritance in JavaScript vs other languages

JavaScript’s original implementation of inheritance was different from other mainstream languages in two ways:

  1. Although most mainstream languages provided class-based inheritance, JavaScript implemented prototypal inheritance.
  2. Furthermore, for the vast majority of programmers, it was not clear how to effectively use inheritance in JavaScript. The syntax was confusing, error-prone, and hard to maintain.

Thankfully, the language has evolved and the syntax for inheritance is now much easier to use and understand.

The updated syntax is akin to Java, and this may lead us to believe that the inheritance model of JavaScript is similar to that of Java—but that’s not true. JavaScript has always provided prototypal inheritance, and this has not changed with the new syntax.

Class-based vs prototypal inheritance

Unlike class-based inheritance, prototypal inheritance is implemented using delegation.

✏️ Remember the sage advice from good design books:

“Delegation is better than inheritance.”

Prototype-based languages like JavaScript take that advice to heart. Although languages like Java, C#, C++, Ruby, and a number of other OO languages provide class-based inheritance, prototype-based languages use an object chain to delegate calls.

Some key differences between the two types of inheritance are:

  • Instead of relying on a base class or superclass, prototypal inheritance relies on the object next in the chain to serve as its base.

  • Class-based inheritance is rather inflexible; once you inherit your class from another class, it’s stuck to the parent.

  • In prototype-based languages, inheritance is dynamic; you may alter the object that serves as the base at runtime. That base object is called the object’s prototype.

Get hands-on with 1400+ tech skills courses.