I'm working with a JavaScript application that uses Underscore.js to handle a lot of inheritance. The standard pattern for object definition is one where the basic object is defined in a variable and then its prototype is defined directly afterwards, like this:
var Parent = function()
{
this.name="parent";
this.loadData();
};
Parent.prototype = {
loadData: function()
{
this.say="parent loadData";
},
action: function()
{
return this.name+" says: '"+this.say+"'";
}
};
This works fine and is reasonably easy to read, but I am a little confused by the way that inheritance is treated in the system. The authors have used the _.extend
method to create a child object in the same format, like this:
var Child = function()
{
this.name="child";
_.extend(this, new Parent());
};
Child.prototype= {
loadData: function()
{
this.say="child data loaded";
}
});
The problem is that although core properties seem to be copied alright, I appear to have the parent rather than child's methods.
var myParent = new Parent();
var myChild = new Child();
console.log( myParent.action() ); // "parent says: 'parent loadData'"
console.log( myChild.action() ); // "child says: 'parent loadData'"
I tried a _.extend( Child.prototype, { ...etc
but that didn't seem to help. Now I could go back to the way I have handled inherited properties in the past Child.prototype.loadData=function()
but it would break the idiom used through the rest of the application, so I'm wondering: Is this is a standard approach to JavaScript object orientation? If so does it have a name/some documentation anywhere? Is there a way to keep this model and have practical inheritance working correctly while retaining readable code?