Apparently in coding there's a thing called inheritance where objects can make baby objects. Just like in real life babies take up certain traits from there parents. Same thing can be said about these baby objects. In this certain instance we're talking about constructor functions and we use these function to create the "baby objects".
To further demonstrate this let's create the parent.
Here we create a constructor function class of feline. Usually the parent or also referred to as "Super" class will consist of properties and methods that all the children will have no matter if they are a different type of feline.
When we create our cat Garfield, we see that he has all the properties of a feline. When we see his object we see the word constructor which will always refer to the constructor function that created the Garfield object which is "Feline". We also see the words proto or in other words prototype which will refer to the parent constructor object. Since we are the parent it appears empty. If you notice at the bottom it says proto: Object in this case this refers to the constructor function that creates ALL objects.
So now what would happen if we want to make lions specifically?
When creating the new child/sub class of Lion we do know that lions have there own distinct properties but we still want all the methods and properties that feline has because a Lion is a feline. In our code in order for our child class of lion to inherit all the properties from the parent class of feline the extends keyword is used.
Now we created a mighty lion of Simba using our lion constructor function. When we take a look at Simba's object, we can see that the constructor in this case is Lion. Now we see that the first proto now has a value of Feline. This is too indicate that the Lion object has a reference to the parent object of Feline with all of it's methods. This is what extends does for us, it sets the prototype to Feline so we can inherit all of it's methods.
Here we see that Simba is able to use purr and ROOOAAR when those functions are invoked. If you saw our constructor function for lion you would notice some code kinda missing. Obviously we don't have the purr method written out or any other methods written out besides just roar.
It's time to explain when the purr method on Simba was invoked the JS interpreter went to the Simba object to see if it has purr. Obviously we never wrote it out in our constructor function so of course it doesn't have it. What it does have is a reference to the parent object of Feline.
Now that the JS interpreter has checked Simba's object and realizes it doesn't have the purr method, it goes and checks the parent object of Feline. In this case it finally finds the purr method and calls it! We made the interpreter put in a bit more work to call the method but it runs pretty fast so I don't feel so bad.
Top comments (0)