gpt4 book ai didi

javascript - window.setInterval 使用局部函数

转载 作者:行者123 更新时间:2023-11-30 10:45:59 27 4
gpt4 key购买 nike

我正在使用 window.setInterval,它必须能够访问在“类”中定义的方法,但是由于 setInterval 在一个与其定义的方法分离的范围,this 解析为 window 而不是所需的 Game 实例。我可以使用什么代码来获得调用 Game.update 而不是 window.update 的所需行为?

(这看起来有点困惑。也许以下不正确的代码可以使事情变得清晰一些。)

game = function () {
/* ... */
this.update = function () {
/* ... */
}
this.interval = window.setInterval(this.update /* !!! */, 50);
}

最佳答案

这可以在没有 JS 框架的情况下完成。

var game = function() {
this.update = function() { }
var that = this;
setInterval(function() {
that.update.apply(that);
},50);
}

关于javascript - window.setInterval 使用局部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8283687/

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