我有一个带有特权方法的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();
我希望每两秒钟收到一次警报,但它只显示警报两次,然后停止。你可以看到live example here。知道为什么会这样吗?
答案 0 :(得分:10)
因为函数外的this
与函数内的this
不同。请尝试改为:
function Test() {
// ... private variables that testMethod needs to access ...
var me = this;
this.testMethod = function() {
alert("Hello, from the method.");
setTimeout(me.testMethod, 2000);
};
}
答案 1 :(得分:6)
首次使用“myTest.testMethod();”调用它时“this”关键字绑定到“myTest”对象,当超时触发“window”对象绑定到“this”关键字时,“this.testMethod”等同于“window.testMethod”。 尝试:
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();
答案 2 :(得分:4)
尝试
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);
};
}
或使用 setInterval 。
答案 3 :(得分:3)
因为你的setTimeout中的this
指的是本地函数testMethod
而不是Test
- 实际上,你是说setTimeout( testMethod.testMethod, 2000 )
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();