【发布时间】:2014-11-26 17:08:18
【问题描述】:
当两个基本函数没有继承关系时,如何创建一个从两个函数继承并尊重其原型更改的函数?
该示例演示了我想要的行为,因为c 对A.prototype 和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
但是,我没有 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