【问题标题】:"Multiple inheritance" in prototypal inheritance原型继承中的“多重继承”
【发布时间】:2014-11-26 17:08:18
【问题描述】:

当两个基本函数没有继承关系时,如何创建一个从两个函数继承并尊重其原型更改的函数?

该示例演示了我想要的行为,因为cA.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 的原型中。
  • 这令人失望 :( 我会继续使用 mixins。

标签: javascript inheritance mixins prototypal-inheritance


【解决方案1】:

这是不可能的。

尝试使用混合模式,或者让 C 的一个属性从 B 继承,另一个属性从 A 继承。 然后通过这些属性访问。

【讨论】:

    【解决方案2】:

    你可以改变你的代码来做这样的事情

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

    【讨论】:

    • 这是一个有趣的方法!但是,我认为我的用例不需要这种复杂性。
    猜你喜欢
    • 2015-10-14
    • 2015-07-07
    • 2017-09-02
    • 2013-11-07
    • 2016-04-03
    • 2019-01-24
    相关资源
    最近更新 更多