Function.prototype.bind 对于 requestAnimationFrame 导致不可读 属性

Function.prototype.bind for requestAnimationFrame results in unreadable property

正在自学 canvas 制作一款我想制作的游戏。

所以我让一切正常,并决定为我的游戏提供自己的对象(我已经有玩家对象等...)。我有一堆注释掉的东西,我稍后会修复。但我现在无法让 RAF 工作。我用 requestAnimationFrame(this.animate) 遇到的第一个错误我用谷歌搜索并修复了。但是这个 Function.prototyping.bind 对我不起作用,因为我收到 Uncaught TypeError: Cannot read property 'bind' of undefined (anonymous function) 作为错误。

Javascript 对我来说是相当新的(我有点决定我离开是有充分理由的哈)。任何帮助将不胜感激。

Game.prototype.animate = function(){
     var that = this;
     setTimeout(function() {

     globalAnimationCancel = requestAnimationFrame(this.animate.bind(this));

//     this.animateObstacles();
//    this.animatePlayer();

//     animatePlayer();
         this.isCollision();
//         this.isLevelUp();
//         this.th

//     isCollision();
//     isLevelUp();
//     thePointCounter.update();
     }, 1000 / fps);
 }

考虑调用发生的地方; setTimeout 正在调用一个 匿名函数 ,您在其中引用了 this。然而,在匿名函数中,this将是window(或undefined),因此没有this.animate 所以不可能有 属性 bind.

要么将它们定义为 setTimeout 之外的变量,这样您就可以在不使用 this 的情况下访问它们,或者设置 var foo = this 并访问所有内容,例如foo.animate。您似乎已经在使用 that 变量但未使用它。


您可以通过尽可能多地移出函数循环来进一步优化

Game.prototype.animate = function(){
    var bound_render;
    function render() {
        console.log(this); // for demo
        // your code to animate goes here
    }
    bound_render = render.bind(this);
    function anim_loop() {
        requestAnimationFrame(bound_render);
        if (true) // some end condition instead of globalAnimationCancel
            globalAnimationCancel = setTimeout(anim_loop, 1000 / fps);
    }
    globalAnimationCancel = setTimeout(anim_loop, 1000 / fps);
}

您可以改为从 函数表达式 创建 bound_render,但我认为将 bind 步骤分开会提高可读性。与 anim_loop 类似,它可以作为 命名函数表达式 直接传递给 setTimeout