为什么赢了';这个Javascript方法不一直在调用自己吗?
我有一个带有特权方法的JavaScript对象。当这个方法完成后,我希望它调用自己(在一个小的超时之后)并无限期地继续运行。不幸的是,该方法只运行了两次,然后就停止了,没有任何错误(在Chrome和IE中测试,结果相同) 代码如下:为什么赢了';这个Javascript方法不一直在调用自己吗?,javascript,methods,settimeout,Javascript,Methods,Settimeout,我有一个带有特权方法的JavaScript对象。当这个方法完成后,我希望它调用自己(在一个小的超时之后)并无限期地继续运行。不幸的是,该方法只运行了两次,然后就停止了,没有任何错误(在Chrome和IE中测试,结果相同) 代码如下: function Test() { // ... private variables that testMethod needs to access ... this.testMethod = function() { alert("
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();
我希望每两秒钟收到一次警报,但它只显示两次警报,然后停止。你可以看到一个。知道为什么会发生这种情况吗?因为函数外部的
与函数内部的不同。请尝试:
function Test() {
// ... private variables that testMethod needs to access ...
var me = this;
this.testMethod = function() {
alert("Hello, from the method.");
setTimeout(me.testMethod, 2000);
};
}
因为setTimeout中的this
指的是本地函数testMethod
而不是Test
——本质上,您说的是setTimeout(testMethod.testMethod,2000)
试一试
或者,当您第一次使用“myTest.testMethod()”调用它时,请使用setInterval,,“this”关键字与“myTest”对象绑定,当超时触发时,“window”对象与“this”关键字绑定,“this.testMethod”相当于“window.testMethod”。
尝试:
或:
我相信setTimeout函数将函数名作为字符串,这就是为什么。不,setTimeout也可以接受函数引用。或者,使用参数。被调用方
进行回调,并完全避免闭包。您应该使用var me=..,如果没有var,您将永远不知道您还更改了什么。对不起,忘记了var
,我已经编辑了答案。(@pst,而不是downvoting,你有足够的代表,你可以自己编辑。)downvote是为了鼓励自我改变:)否则答案是正确的,以后很容易改为upvote。@pst非常感谢你鼓励我自己改变它。或者,使用参数。被调用者
进行回调,并完全避免闭包。+1与当前投票最多的答案不同,这正确地围绕词法变量创建了闭包,self
+1这是一种将闭包移近的聪明方法。它还提到使用setInterval
+1进行更好的解释,并显示了双嵌套闭包方法。我反对大众投票,并选择此作为答案。:)我最感兴趣的是为什么它会这样工作(尤其是为什么setTimeout第一次工作,但第二次却没有)。其他大多数答案都集中在解决办法上。虽然这些都很有帮助,但这并不是我真正想要的。你的回答最清楚地解释了实际发生的事情。。。谢谢无论如何,我不知道为什么我的答案如此受欢迎。
function Test() {
// ... private variables that testMethod needs to access ...
var self = this;
self.testMethod = function() {
alert("Hello, from the method.");
setTimeout(self.testMethod, 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);
};
}
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();