Mic*_*ker 5 javascript methods settimeout
我有一个带有特权方法的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();
Run Code Online (Sandbox Code Playgroud)
ben*_*ado 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);
};
}
Run Code Online (Sandbox Code Playgroud)
当你第一次用"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();
Run Code Online (Sandbox Code Playgroud)
要么:
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();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
258 次 |
最近记录: |