Javascript is meant to be a prototypical language. But unfortunately it is a half done prototypical language. Internally it works like this but externally it tries to looks like something else. To understand this let’s look at the proto property.
Take the following code
1 2 3 4 5 6 7 8 9 10 11 12 |
|
It is extremely easy to see what is happening here. We have just created a prototype inheritance chain between ‘person’ and ‘Animal’. If you ask for a property or method in ‘person’ it will be looked up in that object first, if it is not found there it then will be looked up in the prototype.
proto looks scary because of all the underscores around the name, but in reality it is quite easy and straightforward to understand and use. Unfortunately the proto property is an internal properties only exposed by some browsers (e.g. Chrome, Firefox). So it cannot be used safely.
So sadly we are left with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Note what is happening here:
- We need to create a constructor function
- Then we assign ‘Animal’ as the prototype of that constructor
- Then we run the function to get the instance we want
This is an extremely convoluted process to get to what we want, which is to have an object that inherits from another.
Object.create
There is another alternative which is using Object.create:
1 2 3 4 5 6 7 8 9 10 |
|
Object.create makes a new object with the prototype set to the given object. This is heaps better than the function prototype work around. But still using proto is a lot more intuitive.