Let’s say we have a function.
prototype on that function at the same time. And you can see that another special property
constructor is automatically created on
function.prototype, which is
Animal.prototype.constructor in the above code. You can take the property as the function itself, when we create an instance using something like
What happens under the hood when the above line gets executed is that:
- A new object is created, which is called
- A property called
animal.__proto__is created, and
animal.__proto__ === Animal.prototype.
- It calls
Animal()in the context of
animal,which means following lines get executed.
So let’s sum up what happens here with a diagram.
animal.__proto__is the same as
Nothing is wrong here, we get all of animal’s custom properties(
food) with or without
__proto__, so what is it used for? Let’s add a line here.
This is where the interesting part comes in. We know that
animal doesn’t have a property called
Animal.prototype to see if
Animal.prototype has a property called
walk property itself!
In this way, we can define another object called
Cat, which inherits from
cat has all properties that we defined in
walk, and our
cat even overrides
food, because we all know, cat likes to eat
But do you know how
cat.walk === 'aniamls can walk' works? It follows several steps.
- Check if
cathas a property called
walk, obviously it doesn’t have that.
- Check if
cat.__proto__, which is
Cat.prototype, which is also
animalhas that property, obviously
animalalso doesn’t have it.
- Check if
walkproperty, OK, this time
walkproperty, return its value, the job is done here.
So you can see,
__proto__ is just like a chain, to check if an instance
cat has a property
walk, we need to check:
cat.__proto__ is the same thing as
Cat.prototype, to inherit
Animal, what we need to do is just point
cat could have all properties
animal has in this way.
One thing is left here. We find out that
[Function: Animal], this may not be what we want.
cat is created by
Cat instead of
Animal, so we need to add another line here.
This is the complete code.
Let’s make it more concise.
This can also be written as
In fact, we also need to do anther things like changing the super class of
Cat, so a function called
Object.inheritance was created to do this sort of work, which would modify the super class of the child class and set the child class’ prototype as the parent’s.
That’s it, the above code is one of the most common ways to achieve inheritance.