Helping myself better understand Prototypal inheritance in Javascript.
It was a nightmare, I was in the middle of a technical interview and was being asked some questions about Javascript, the interviewer then asked me to talk a little about prototypal inheritance and I froze. I’m fairly new to programming and thought that I had a good understanding of Javascript fundamentals, but when put on the spot to really flex what I knew I realized that my shallow understanding of some aspects of Javascript just wouldn’t cut it professionally.
So here I am, using this blog to really cement prototypal inheritance into my brain and I hope by doing so might help a few other people along the way.
Prototypal Inheritance is when one object can use another object’s properties and methods and is what is behind the scenes of ES6’s classes and extends keywords. Every object in Javascript comes with a property called prototype, this property is what makes prototypal inheritance possible.
Let's further examine how this works with some code.
We’ll start by building a constructor to build a blueprint of a Dog object
We’ve given our Dog constructor object a few arguments of breed, color, and weight, then we use the this keyword which refers to the Dog constructor itself along with the arguments to finish our blueprint.
Now we can create a few instances of a dog using the blueprint we have just created. When we create a new dog we give it all the corresponding arguments from our blueprint. For example with our pug, when he is created he has a breed of pug, the color of black and a weight of 5.
So now that we have instantiated a few dogs let's create a method to fatten up these pups using the built-in prototype property.
Now if we console.log our two dogs we can see that they have the fatten function added to them via the prototype property.
Now that we have created our fatten method and can see that our two dogs have the method through the prototype property we can use it on our pups.
Now, this is just a very simple example and I hope to cover more on how classes can inherit from one another in a very similar way and also get into the prototype chain in my next blog. I hope this has been helpful!