0

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
hgoebl
  • 12,637
  • 9
  • 49
  • 72
Steven Wexler
  • 16,589
  • 8
  • 53
  • 80

2 Answers2

2

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.

Etai
  • 1,483
  • 1
  • 11
  • 15
1

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');
Paul S.
  • 64,864
  • 9
  • 122
  • 138