function UITimer(interval, callbakFunction) {
this.t = null;
this.isRunning = 0;
this.interval = interval;
this.callbackFunction = callbakFunction;
};
UITimer.prototype.timeCount = function () {
alert(this.interval);
this.callbackFunction();
this.t = setTimeout(this.timeCount, this.interval);
}
UITimer.prototype.startTimer = function () {
if (!this.isRunning) {
this.isRunning = 1;
this.timeCount();
}
}
UITimer.prototype.stopTimer = function () {
clearTimeout(this.t);
this.isRunning = 0;
}
var uiTimer = new UITimer(5000, PhotoService.GetRandomImage);
uiTimer.startTimer();
第一次this.interval = 5000
,第二次undefined
。我将间隔替换为常量值,但此行this.t = setTimeout(this.timeCount, 5000);
无法第二次运行。有什么问题?
答案 0 :(得分:3)
传递函数时this
值会丢失。 foo.bar()
this
将foo
设置为bar
内的.bind
,但在存储/传递值并稍后调用时,这不会发生。
使用this
强制timeCount
内的this.t = setTimeout(this.timeCount.bind(this), this.interval);
值:
timeCount
或者,传递另一个调用this
的函数。请注意,由于this
更改了函数内部,因此您必须保存对正确的var _this = this; // won't change
this.t = setTimeout(function() {
_this.timeCount(); // `_this` is the correct `this`
}, this.interval);
值的引用:
{{1}}