简体   繁体   中英

“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

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.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM