这是我使用window.setinterval来增加window.setinterval值的代码。
var Arrow = (function () {
function Arrow() {
this.intVariable = 1;
this.itemId = -1;
this.interval = 25;
}
Arrow.prototype.activateTimer = function () {
if (this.itemId === -1) {
window.setInterval(this.showTimer(), this.interval);
}
};
Arrow.prototype.showTimer = function () {
this.intVariable += this.interval;
console.log(this.intVariable);
};
return Arrow;
}());
var arrow = new Arrow();
arrow.activateTimer();
当我使用下面一行时,仅调用一次显示计时器函数。
window.setInterval(this.showTimer(), this.interval);但当我把它改为:
window.setInterval(() => this.showTimer(), this.interval);它工作得很完美。
需要一些帮助,为什么它使用箭头函数工作。
发布于 2017-07-31 06:53:08
您应该向interval提供函数,而不是函数的返回。
无论何时编写window.setInterval(this.showTimer(), this.interval);,实际上都是这样做的。
var returnValue = (function () {
this.intVariable += this.interval;
console.log(this.intVariable); // You get your log for once
})() // -> null
window.setInterval(returnValue/*null*/, this.interval);然后,setInterval尝试在每个this.interval之后调用null,这不会在控制台上出现错误。
但是,当您用箭头() => this.showTimer()调用它时,这意味着:
var returnValue = function() {
this.showTimer();
} // -> Function
window.setInterval(returnValue/*Function*/, this.interval);您正在为interval提供一个函数。
此外,如果忘记将函数绑定到this作用域,则无法访问箭头作用域。因此,您可能会看到许多NaN的
setInterval尝试用全局范围(即window )调用已注册的函数。因此,当您在函数中编写this时,它将使用this作为window。因此,每当您尝试记录this.intVariable时,它都会尝试记录未定义的window.intVariable。
因此,我们应该将我们的函数绑定到当前的对象范围。因此,每当您使用this时,您的作用域将绑定到当前对象(Arrow)。得到当前的箭头intVariable。
但是,无论何时编写() =>,都会像上面那样创建匿名函数,并且已经将其作用域连接到对象中。这样你就不需要额外的绑定了。
这是你的解决方案
var Arrow = (function () {
function Arrow() {
this.intVariable = 1;
this.itemId = -1;
this.interval = 25;
}
Arrow.prototype.showTimer = function () {
this.intVariable += this.interval;
console.log(this.intVariable);
};
Arrow.prototype.activateTimer = function () {
if (this.itemId === -1) {
window.setInterval(this.showTimer.bind(this), this.interval);
}
};
return Arrow;
}());
var arrow = new Arrow();
arrow.activateTimer();这是一个小提琴
发布于 2017-07-31 06:50:47
您可以直接使用函数引用(不使用括号)
window.setInterval(this.showTimer, this.interval);通过使用函数调用,
window.setInterval(this.showTimer(), this.interval);
// ^^插入函数调用的结果,而不是函数本身。
当你使用
window.setInterval(() => this.showTimer(), this.interval);您插入一个函数,而不实际调用它。
发布于 2017-07-31 06:52:55
window.setInterval(() => this.showTimer(), this.interval);就像
window.setInterval(function() {this.showTimer()}, this.interval);
window.setInterval(this.showTimer(), this.interval);不工作,因为您只需要传递this.showTimer,但您正在动态调用它
https://stackoverflow.com/questions/45409107
复制相似问题