[英]“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
. 该示例演示了我想要的行为,因为
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
However, I don't have the luxury where B inherits from A. 但是,我没有奢侈的地方,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
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. 尝试使用混合模式,或者让C的属性从B继承,另一个属性从A继承。然后通过这些属性进行访问。
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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.