这是我使用 window.setinterval 增加 intVariable 值的代码。
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();
当我在下面使用时,show timer 函数只被调用一次
window.setInterval(this.showTimer(), this.interval);
但是当我把它改成:
window.setInterval(() => this.showTimer(), this.interval);
它完美地工作。
需要一些帮助,了解为什么它使用箭头函数起作用。
最佳答案
您可以直接使用函数引用(不使用括号)
window.setInterval(this.showTimer, this.interval);
通过使用函数调用,
window.setInterval(this.showTimer(), this.interval);
// ^^
您插入函数调用的结果而不是函数本身。
当你使用
window.setInterval(() => this.showTimer(), this.interval);
你插入了一个函数,但实际上并没有调用它。
关于javascript - 混淆了箭头函数javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45409107/