gpt4 book ai didi

javascript - 原型(prototype)继承中的"Multiple inheritance"

转载 作者:行者123 更新时间:2023-11-28 19:29:27 24 4
gpt4 key购买 nike

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

该示例演示了我想要的行为,因为 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

最佳答案

这是不可能的。

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

关于javascript - 原型(prototype)继承中的"Multiple inheritance",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27154991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com