2012-02-11 51 views
0

我有这样的例子。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中复制时不起作用?可能以某种方式在两种功能之间制造这种类型的门?

+0

检测到递归。 – 2012-02-11 18:15:26

回答

2

apply调用函数,使用您指定的任何this

想一想。如果Foo调用Bar,并且Bar调用Foo,那么最终会出现无限递归。你需要某种方式来说“不要再拨打Foo”。或者至少,Foo需要能够看到“嘿,我已经被召唤过一次了,这次不做任何事情”。

但是,事实上,你需要做任何的气味。你通常不需要这样的循环依赖;如果两件东西互相缠绕在一起,以至于它们需要对方的功能才能起作用,那么听起来好像你可能能够将交织在一起的东西分成一个单独的类型,并且从那里使用FooBar,或者都可以从中继承, 或者其他的东西。但我需要看到更多的设计才能说出任何具体的东西。

相关问题