Helping myself better understand Prototypal inheritance in Javascript. Part 2.
In my last blog, I demonstrated the very basics of prototypal inheritance. We started by building a constructor that would be the blueprint for a Dog object, then we used the blueprint to build out a couple of dogs with corresponding attributes. Once we had our Dog constructor and our dogs we created with it, we added a method to the built-in prototype property called fatten() that would increase the weight of our dogs by one and then console.log the proof of it. We then just called our new method on our two dogs and saw them both fatten by one using prototypal inheritance. This is our code as it stands:
The next thing I’d like to expand upon for my own deeper understanding is the prototype chain.
So let's say instead of having pug just be an instance, we wanted it to be a class but still be able to inherit just as it did before, we can!
We will start by making our Pug class.
Next, we’ll create a new object that is based on our Dog prototype and assign it to our Pug prototype, we do this by using javascript’s Object.create.
We can then replace our pug variable from being equal to the new Dog to the new Pug class and console.log with the fatten() method as we did before. Let's see what happens.
Hmm, undefined and NaN… What we need to do is that now that our Pug class has access to the Dog constructor, we can use it within our new Pug class with the Dog.call() method. The arguments for the call() method will consist of the this keyword and the associated arguments that the this keyword refers to in the Dog constructor and now are fatten() method should work again like normal.
Our Pug class knows about the fatten() method through something called the prototype chain. Let’s look deeper into this with a console.log to examine the Pug class.
When we look at our Pug class in the console, we can see that by digging through the __proto__ object we can chain through the inheritance until we find the fatten() method we created on the Dog constructor. This is the prototype chain. Thanks, Javascript!
ES6 now has syntactic sugar with class keywords and extends keywords that give javascript a similar feel to other languages when it comes to class inheritance, but it’s always good to know what’s happening behind the scenes.