What’s going on here?
Above we have defined a method that accepts two constructor functions.
A represents the base class which we a extending from, and
B represents the class which will extend from
A. The routine goes as follows:
- Create a new temporary function.
- Overwrite the temporary function’s prototype object with A’s prototype object.
- Overwrite B’s prototype object with an instance of the temporary class
F. This means
B’s protype is now an empty object with it’s own prototype…
A.prototype, we have extended the ‘prototype chain’.
B’s direct prototype now no longer has a
constructorproperty, so, incase anyone wants to use this property, we must re-set it.
The prototype chain
Under the hood all we’re doing is extending the
Animal.prototype, adding a new object to the top of the chain and defining additional properties on that object. In this case the chain looks as follows:
When a property is accessed on the instance, the JS runtime will check each layer of the prototype (shallowest to deepest) until the property is found. If the property is not found on the last layer of the prototype,
undefined is returned.
NOTE: There are performance issues that come from extending the prototype chain too far. I’ve found there is rarely reason to be extending more than one layer deep. Keep the inheritance chain as short as possible.
Object.create has been available and can simplify the process even further.
In my experience I’ve found very few cases that genuinely require inheritance. It can sometimes seem like a good idea at the time, but in the long run can end up over complicating things. My advice for most cases would be: try to use composition over inheritance, keep relationships simple.