我有这样的例子。JS OOP。继承和apply()函数。为什么它不起作用?
function Bar() {
this.barVal = "BarValue";
}
function Foo() {
this.fooVal = "FooValue";
Bar.apply(this, arguments); // here I use apply() to get access everything in Bar from Foo;
}
var barObj = new Bar;
var fooObj = new Foo;
alert(fooObj.barVal); // the output is `BarValue`
现在我想以同样的方式从酒吧拿到美孚获得的一切。我修改我的代码:
function Bar() {
this.barVal = "BarValue";
Foo.apply(this, arguments); // I add the same line of code, just change names
}
function Foo() {
this.fooVal = "FooValue";
Bar.apply(this, arguments); // and also leave it here because I want previous functionality too
}
var barObj = new Bar;
var fooObj = new Foo;
alert(fooObj.barVal);
alert(barObj.fooVal); // there is no any output for both
但是没有任何输出。我其实发生了一些错误。当我在评论下隐藏Foo.apply(this, arguments);
时,电话alert(fooObj.barVal);
再次运作。当我检查它像这样:
function Bar() {
this.barVal = "BarValue";
try {
Foo.apply(this, arguments);
}
catch(e) {
alert(e);
}
}
甚至停止浏览器的工作(我使用Chrome这样整个blaсk屏幕像素文件夹中出现)。而在警报窗口写入RangeError: undefined
但正如我在这个序列中
alert(fooObj.barVal);
alert(barObj.fooVal);
警报呼叫的第二警报显示正是我等待它 - 它显示BarValue
。
为什么apply()在Bar中复制时不起作用?可能以某种方式在两种功能之间制造这种类型的门?
检测到递归。 – 2012-02-11 18:15:26