Search code examples
javascriptinheritancemixinsprototypal-inheritance

"Multiple inheritance" in prototypal inheritance


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

Solution

  • 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.