简体   繁体   English

为什么在间隔循环中定时器实例中的属性未定义?

[英]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.

相关问题 为什么在类方法中使用我的实例属性时未定义? - Why is my instance property undefined when used in a class method? AngularJS $ interval显示计时器(当间隔过去时) - AngularJS $interval displays timer (when the interval will elapse) 对象实例为其原型属性输出“ undefined”。 为什么? - Object instance outputs `undefined` for it's Prototype's property. Why? 为什么在我调用functions属性时未定义? - Why is this undefined when I call a functions property? 为什么对象在输出属性时返回 undefined? - Why the object returns undefined when output property? 为什么我在此 for 循环中无法读取未定义的属性“startsWith”? - Why am I getting Cannot read property 'startsWith' of undefined in this for loop? for循环检查属性是否未定义? - For loop to check property is not undefined? 为什么实例变量未定义? - Why is instance variable undefined? Javascript-为什么循环? 实例->(原型属性->构造函数属性->功能对象->构造函数属性) - Javascript - why this loop ? instance->(prototype property->constructor property->function object->constructor property) 带有React的计时器无法读取未定义的属性秒 - Timer with React cannot read property seconds of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM