gpt4 book ai didi

javascript - 使用 requestAnimationFrame 的 JS 游戏循环 - 对象函数仅调用一次

转载 作者:行者123 更新时间:2023-11-28 20:18:23 24 4
gpt4 key购买 nike

抱歉,我在 js 方面是个菜鸟,以为我掌握了对象实例和函数的基础知识,结果我不知道也不知道如何弄清楚该怎么做。

我已经声明了一个 GameLoop 函数/对象,如下所示:

function GameLoop() {

window.requestAnimationFrame =
window.requestAnimationFrame || /* Firefox 23 / IE 10 / Chrome */
window.mozRequestAnimationFrame || /* Firefox < 23 */
window.webkitRequestAnimationFrame || /* Safari */
window.msRequestAnimationFrame || /* IE */
window.oRequestAnimationFrame; /* Opera */

this.start = function() {
this.update();
};

this.update = function() {
this.processInput();
this.updateState();
this.updateGraphics();
window.requestAnimationFrame(this.update);
};

this.processInput = function() {
alert("pi");
};

this.updateState = function() {
alert("us");
};

this.updateGraphics = function() {
alert("ug");
};

};

我正在尝试像这样运行它:

$(document).ready(main);

function main() {
var gameLoop = new GameLoop();
gameLoop.start();
}

发生的情况是,每个“processInput”、“updateStaten”和“updateGraphics”函数都被调用一次(我可以看到显示的每个警报),但随后它停止并出现错误(在 Firefox 的错误控制台内)是

Error: TypeError: this.processInput is not a function

指向 update 函数内的 this.processInput() 行。

我只是不明白为什么,尤其是第一次调用函数时。有人可以帮忙吗?

最佳答案

您的函数正在使用错误的 this 运行。

this 是根据您调用函数的方式设置的。
当被 requestAnimationFrame 调用时,this 将是 window

要解决此问题,您需要将 this 保留在闭包中:

var self = this;
requestAnimationFrame(function() { self.processInput(); });

您还可以使用新的 ES5 bind() 函数来为您执行此操作:

requestAnimationFrame(this.processInput.bind(this));

关于javascript - 使用 requestAnimationFrame 的 JS 游戏循环 - 对象函数仅调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18812704/

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