Reputation: 545
Why this type of inheritance will not work in JavaScript. Is there any way to perform this step. Please help
function base() {}
base.prototype.findFirst = function() {
console.log("FindMe First");
}
function base2() {}
base2.prototype.findMe = function() {
console.log("FindMe ");
}
function inherit() {
base.call(this);
base2.call(this);
}
inherit.prototype = base.prototype;
inherit.prototype.constructor = inherit;
inherit.prototype = base2.prototype;
inherit.prototype.constructor = inherit;
var test = inherit();
test.findFirst();
test.findMe();
Upvotes: 0
Views: 133
Reputation: 684
Mixins can be used in javascript to achieve the same goal you probably want to solve via multiple inheritance at the moment.
Upvotes: 1
Reputation: 755
You are overwritting prototype with base.prototype and then with base2.prototype. So it stores base2.prtotype i.e. which is assigned second. Now if you create an instance of your inherit class
var test = new inherit();
you will see that test has base2.property i.e. it has fimeMe()
method in test.property.findMe();
.
To achieve your goal you should try to extend or refer
Mixin
Multiple Inheritance
Upvotes: 2
Reputation: 12655
I've extended the Function
prototype which is not the best idea, but to give you an idea of how it works. It's not multi inheritance, but it's an inheritance tree.
Function.prototype.extend = function(child)
{
var childPrototype = child.prototype;
child.prototype = Object.create(this.prototype);
for (var property in childPrototype) {
if (childPrototype.hasOwnProperty(property)) {
child.prototype[property] = childPrototype[property];
}
}
child.prototype.constructor = child;
return child;
};
var base = (function()
{
var base = function()
{
};
base.prototype.findFirst = function(x, y)
{
console.log("FindMe First");
};
return base;
}());
var base2 = base.extend(function()
{
var base2 = function()
{
};
base2.prototype.findMe = function(x, y)
{
console.log("FindMe ");
};
return base2;
}());
var inherit = base2.extend(function()
{
var inherit = function()
{
};
return inherit;
}());
var test = new inherit();
test.findFirst();
test.findMe();
Upvotes: 0