为什么这个 Javascript 方法不会继续调用自身?
我有一个带有特权方法的 JavaScript 对象。当此方法完成后,我希望它调用自身(在短暂的超时后)并继续无限期地运行。不幸的是,该方法只运行两次,然后就停止了,没有任何错误(在 Chrome 和 IE 中测试,结果相同)。
代码如下:
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 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).
The code is as follows:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为函数外的
this
与函数内的this
不一样。尝试改为:Because
this
outside the function is not the same asthis
inside the function. Try instead:当您第一次使用“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:
Or:
尝试
或使用setInterval。
Try
or use setInterval.
因为 setTimeout 中的
this
指的是本地函数testMethod
而不是Test
——本质上,你是在说setTimeout( testMethod.测试方法,2000)
because the
this
in your setTimeout is referring to the local functiontestMethod
notTest
-- essentially, you are sayingsetTimeout( testMethod.testMethod, 2000 )