...

/

Understanding Prototypal Inheritance

Understanding Prototypal Inheritance

Deep dive into the basics of prototypal inheritance, prototype chaining, getters, and setters in JavaScript.

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 ...