Last Updated: February 4, 2023
JavaScript Prototypal Inheritance
How inheritance works in JavaScript
Inheritance is mainly used to help reduce code duplication, meaning you don’t have to write the same code over and over again. It’s typically associated with Classes, for most people and most programming languages.
Inheritance in JavaScript is done through Prototypal Inheritance. If that sounds like gibberish to you then you're in the right place.
Today we’re gonna explore the concept of inheritance, and how it works specifically in JavaScript. Inheritance in JavaScript is a little different than other languages, and confusing to say the least.
const me = { talk() { return 'Hello'; } } const you = { talk() { return 'Hello'; } } me.talk(); // 'Hello' you.talk(); // 'Hello'
Immediately we have two problems:
Problem 1: we had to write the talk
function
twice!
When you repeat the same thing, or code, chances are there is a better way to do it.
Now you might look at this code and say: 'hey, what's the big deal? It's just one line. So what if I have to repeat it?' Well, In most real-life programs your functions are not simple one-liners. They're probably a lot more complicated than that, so repeating them becomes more obvious as a problem.
But even then, it's fair to ask why it's such a big deal to copy logic just once? Again, in real world scenarios you probably don't have just two objects. What you have a me
object, a you
object, a he
object, a she
object, and a they
object? You're going to copy the code that many times? I don't think so.
Problem 2: changing the logic would means multiple changes.
If we happen to find a bug, or decide to change the logic of the talk
function for any reason, it would mean making the same change multiple times and that is inefficient and error-prone.
One way to avoid these problems is using inheritance.
Inheritance using Classes
class Person { talk() { return 'Hello'; } } const me = new Person(); const you = new Person(); me.talk(); // Hello you.talk(); // Hello
Great! We solved both of the problems that were caused by duplication. We only had to write the function once, and if we ever need to update the logic we only have to make the change once.