【发布时间】:2013-05-13 16:26:09
【问题描述】:
使用节点但在 JavaScript 中寻找钻石继承的方法:
var util = require('util');
function Base(example_value) {
console.log(example_value);
this.example_property = example_value;
this.example_method = function() { ... };
}
function Foo(settings) {
var f = settings.f;
Base.call(x);
this.settings = settings;
}
util.inherits(Foo, Base);
function Bar(settings) {
var b = settings.b;
Base.call(b);
this.settings = settings;
}
util.inherits(Bar, Base);
var foo = new Foo({f: 'bar'});
// 'bar' gets printed and I can call methods from Base..
foo.example_method();
var bar = new Bar({b: 'foo'});
// 'foo' gets printed and I can call methods from Base..
bar.example_method();
这里没有问题..但是我需要在另一个包罗万象的对象中制作 Foo 和 Bar(和 Base)中可用的所有内容:
function Top(settings) {
Foo.call(this, settings);
Bar.call(this, settings);
}
util.inherits(Top, Foo);
util.inhertis(Top, Bar);
var top = new Top({some: 'value'});
'value' 被打印两次,这不是我想要的。像这样进行继承可能不是最好的方法,因此寻找替代方案/建议来处理这种菱形结构。
附:没有包含原始代码,但经过修改以希望简化 - 我是手工完成的,不认为有任何错误,但我试图理解的重点应该在那里。
【问题讨论】:
-
我根本看不到“value”是如何打印的,因为“settings”对象既没有“f”也没有“b”属性。
-
@Pointy:
f和b在构造函数参数中设置(例如var foo = new Foo({f: 'bar'});)。 -
@Cory 是的,并且函数“Top”是使用具有名为“some”的单个属性的对象调用的。 “Top”函数传递它传递给“Foo”和“Bar”的对象。
-
@Pointy:好的,我明白了。鉴于“'value' 被打印两次”,我认为示例代码是错误的。
-
抱歉,example_value 被打印了两次。感谢您选择此内容