簡體   English   中英

原型繼承中的“多重繼承”

[英]“Multiple inheritance” in prototypal inheritance

當兩個基本函數沒有繼承關系時,如何創建一個從兩個函數繼承並尊重其原型更改的函數?

該示例演示了我想要的行為,因為c修改了A.prototypeB.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

但是,我沒有奢侈的地方,B繼承了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

這是不可能的。

嘗試使用混合模式,或者讓C的屬性從B繼承,另一個屬性從A繼承。然后通過這些屬性進行訪問。

您可以更改代碼以執行以下操作

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];
}

然后像

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM