gpt4 book ai didi

javascript - JavaScript 中的类变量和 setInterval

转载 作者:行者123 更新时间:2023-11-28 16:02:10 25 4
gpt4 key购买 nike

由于如果我需要参数,我需要将匿名函数传递给 setInterval,因此我尝试使用以下代码。最初我让它调用 this.countUp ,但是当它返回 NaN 时,我做了一些阅读并找到了 .call(this) 解决方案。然而,当我将其与匿名函数(我承认我对此有点模糊)结合起来时,我现在在 Firebug 中收到 TypeError: this.countUp is undefined

我想我不需要使 count 可访问,也不需要使 playBeep 方法可访问,但让我们假设我想要这样做,以便我可以理解我在做什么这段代码有问题。

    function workout() {
var beep = new Audio("beep1.wav");
this.timerWorkout; //three timers in object scope so I can clear later from a different method
this.timerCounter;
this.timerCoolDown;
this.count = 0;

this.startWorkout = function() {
alert(this.count);
this.timerWorkout = setTimeout(this.playBeep, 30 * 1000); //workout beep - 30 seconds
this.timerCounter = setInterval(function() {this.countUp.call(this)}, 1000); //on screen timer - every second

}

this.startCoolDown = function() {
this.timerCoolDown = setTimeout(this.playBeep, 10 * 1000); //cooldown beep - 10 seconds
}

this.playBeep = function() {
beep.play(); //plays beep WAV
}

this.countUp = function() {
this.count++;
document.getElementById("counter").innerHTML = this.count;
}

}

var workout1 = new workout()

最佳答案

startWorkout内部使用bind(this):

this.timerCounter = setInterval(function() {this.countUp()}.bind(this), 1000);

关于javascript - JavaScript 中的类变量和 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16610762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com