[英]Why is property undefined in timer instance when in interval loop?
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();
The first time this.interval = 5000
, second time it is undefined
. 第一次
this.interval = 5000
,第二次是undefined
。 I replaced the interval by a constant value but this line this.t = setTimeout(this.timeCount, 5000);
我用一个常量值替换了这个区间,但是这一行是
this.t = setTimeout(this.timeCount, 5000);
could not run the second time. 无法第二次运行。 What is the problem?
问题是什么?
The this
value gets lost when passing a function. 传递函数时,
this
值会丢失。 foo.bar()
sets this
to foo
inside bar
, but when storing/passing the value and calling it later, this does not happen. foo.bar()
将this
设置为foo
里面的bar
,但是当存储/传递值并稍后调用它时,这不会发生。
Use .bind
to force the this
value inside timeCount
: 使用
.bind
this
值强制放入timeCount
:
this.t = setTimeout(this.timeCount.bind(this), this.interval);
Or, pass another function that calls timeCount
. 或者,传递另一个调用
timeCount
函数。 Beware though, since this
changes inside functions, you'd have to save a reference to the correct this
value: 请注意,因为
this
更改内部函数,所以您必须保存对正确this
值的引用:
var _this = this; // won't change
this.t = setTimeout(function() {
_this.timeCount(); // `_this` is the correct `this`
}, this.interval);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.