为什么这个Javascript方法不会自己调用? [英] Why won't this Javascript method keep calling itself?
问题描述
我有一个带有特权方法的JavaScript对象。当这个方法完成后,我希望它自己调用(在一个小的超时后)并继续无限期地运行。不幸的是,该方法只运行两次,然后停止没有任何错误(在Chrome和IE中测试,结果相同)。
I have a JavaScript object with a privileged method. When this method has completed, I would like it to call itself (after a small timeout) and continue running indefinitely. Unfortunately, the method only runs twice, then it stops without any error (tested in Chrome and IE with the same results).
代码如下:
function Test() {
// ... private variables that testMethod needs to access ...
this.testMethod = function() {
alert("Hello, from the method.");
setTimeout(this.testMethod, 2000);
};
}
var myTest = new Test();
myTest.testMethod();
我希望每两秒钟收到一次警报,但它只显示警报两次,然后停止。您可以在此处查看实时示例。知道为什么会发生这种情况吗?
I would expect to get the alert every two seconds, but instead it only shows the alert twice, then stops. You can see a live example here. Any idea why this would be happening?
推荐答案
当你第一次用myTest.testMethod();调用它时this关键字绑定到myTest对象,当超时触发window对象绑定到this关键字时,this.testMethod等同于window.testMethod。
尝试:
When you first call it with "myTest.testMethod();" the "this" keyword is bond to your "myTest" object, when the timeout fires the "window" object is bond to "this" keyword and "this.testMethod" is equivalent to "window.testMethod". Try:
function Test() {
// ... private variables that testMethod needs to access ...
this.testMethod = function() {
alert("Hello, from the method.");
setTimeout((function(self){
return function(){self.testMethod();};
})(this), 2000);
};
}
var myTest = new Test();
myTest.testMethod();
或者:
function Test() {
// ... private variables that testMethod needs to access ...
this.testMethod = function() {
alert("Hello, from the method.");
var self = this;
setTimeout(function(){self.testMethod();}, 2000);
};
}
var myTest = new Test();
myTest.testMethod();
这篇关于为什么这个Javascript方法不会自己调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!