I’ve come across a behaviour of the function object. that seems to be similar to prototyping but uses a different method.
var Car = function() {
this.foo = 'shiny';
}
var Rover = function() {
this.inherit = Car;
this.inherit();
}
var Mini = function() {
this.inherit = Car;
this.inherit();
}
when a new instance of a sub class is made this.inherit method has the effect of calling the parent class on itself, so that the parent’s properties and methods are available to the sub class.
var myRover = new Rover();
var myMini = new Mini();
myMini.foo = 'rusty';
console.log(myRover.foo, myMini.foo); // displays "shiny" & "rusty" respectively
I’ve looked in Mozilla and MSDN, but I can’t seem to find it documented any where. Can anyone put a name to this behaviour and any further documentation.
I think the word
inheritFromdoes not make any sense here. It could be as wellbar. What makes this work is the pattern that you define a member of the “subClass” function which you call on the next line.It may be worth checking out “Classical Inheritance in JavaScript” article by Douglas Crockford for some additional ideas.