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

标签 javascript function object

抱歉,我在 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/

相关文章:

Javascript 测试对象是否有任何未定义或为 null 的键

javascript - leetcode 如何做到这一点 : Read user's input String as multiple JavaScript functions and run a main function with user's input params

javascript - 他们如何在鼠标悬停时隐藏 URL?

function - 在 CartoDB 中创建触发器和函数

javascript - 连接字符串作为对象属性

excel - 错误处理不处理

javascript - 如何在 react 中处理条件渲染

arrays - SELECT 查询与 PostgreSQL 的 FUNCTION 性能问题

swift - 在将另一个方法作为参数传递的方法中,为什么 passes 参数不需要传递其参数?

object - JavaScript:对象[全局对象]没有方法