"Multiple inheritance" in prototypal inheritance

98 Views Asked by At

How can I create a function that inherits from two functions and respects changes for their prototypes when the two base functions don't have an inheritance relationship?

The example demonstrates the behavior I want because c gets modifications to A.prototype and B.prototype.

function A() { }
function B() { }
B.prototype = Object.create(A.prototype);
function C() { }
C.prototype = Object.create(B.prototype); 

A.prototype.foo = "foo";
B.prototype.bar = "bar";

var c = new C();
console.log(c.foo); //prints foo
console.log(c.bar); //prints bar

However, I don't have the luxury where B inherits from A.

function A() { }
function B() { }
function C() { }
C.prototype = //something that extends A and B even though B does not extend A.

A.prototype.foo = "foo";
B.prototype.bar = "bar";

var c = new C();
console.log(c.foo); //should print foo
console.log(c.bar); //should print bar
2

There are 2 best solutions below

0
On BEST ANSWER

This is not possible.

Try using a mixin pattern, or have a property of C inherit from B and another property inherit from A. Then access through these properties.

1
On

You could change your code to do something like this

C.prototype.perform = function (key) {
    var args = Array.prototype.slice(arguments, 1);
    if (key in this)
        return this[key].apply(this, args);
    if (key in B.prototype)
        return B.prototype[key].apply(this, args);
    if (key in A.prototype)
        return A.prototype[key].apply(this, args);
    undefined(); // throw meaningful error
}

C.prototype.get = function (key) {
    if (key in this)
        return this[key];
    if (key in B.prototype)
        return B.prototype[key];
    if (key in A.prototype)
        return A.prototype[key];
}

Then use it like

var c = new C();
c.perform('toString');
c.get('foo');