JavaScript Fundamental: Prototypal Inheritance

As a JavaScript developer, knowing how inheritance works in JavaScript is an essential knowledge that will come very handy during interviews (hint hint). Today, I want to take the time to walk through inheritance in JavaScript and good/bad of JavaScript’s inheritance.
With that said, let’s get right into it!
Inheritance
What is an inheritance?
An inheritance is one of the four fundamental concepts (Abstraction, Encapsulation, Inheritance, and Polymorphism) of object-oriented programming. Inheritance enables one object to take properties of another existing object.
Does JavaScript have inheritance?
Yes! Specifically, JavaScript uses a type of inheritance called prototypal inheritance which is quite different from classical inheritance used by languages like Java.
Prototypal Inheritance
What is prototypal inheritance?
To understand prototypal inheritance, we first need to understand prototype chain. A prototype chain is a series of linkage between each object to its prototype which serves as a “parent object” in a way until the chain reaches a reference to null. Also, prototype of an object can be set manually using __proto__. Let’s take an example:
const vehicle = { numWheels: 4}
const car = { numDoors: 4}
// Setting vehicle as car object's prototype
car.__proto__ = vehicle
console.log(car.numWheels)
=> 4Notice that car object doesn’t contain a property called numWheels but when we set the vehicle object as its prototype, car.numWheels is equal to 4. In prototypal inheritance, if a property doesn’t exist in the original object, JavaScript will start searching for the property from the original object’s prototype and keep moving up the prototype chain until it either finds the property or reaches null.
Good or bad?
This can be different for each person. I personally think it’s good and bad at the same time for these reasons:
Good…
- Easy and simple
- Suits JavaScript’s nature of being dynamic
- Less redundancy is the code base
Bad…
- Potentially hard to grasp for people used to classical inheritance (eg. Java)
- JavaScript’s prototypal inheritance uses a constructor pattern where objects inherit from constructors of another object rather than the whole object which I believe aligns more to what prototypal inheritance tries to achieve
If you are like me and want to learn more about how JavaScript was designed/created from the creator (Brendan Eich) himself, you can also check out his tech talk.
“I was under marketing orders to make it look like Java but not make it too big for its britches. It’s just this sort of silly little brother language, right? The sidekick to Java.” — Brandan Eich (Creator of JavaScript)






