为什么此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屋!