Javascript requestAnimationFrame的Function.prototype.bind导致属性不可读

Javascript requestAnimationFrame的Function.prototype.bind导致属性不可读,javascript,canvas,html5-canvas,Javascript,Canvas,Html5 Canvas,我正在努力教自己制作一个游戏的画布 所以我让一切都正常工作,并决定给我的游戏赋予它自己的对象(我已经有了玩家对象,等等)。我有一大堆被注释掉的东西,稍后我会修复。但我现在不能让皇家空军去工作。我在谷歌搜索并修复了requestAnimationFrame(this.animate)时遇到的第一个错误。但是这个Function.prototyping.bind不适用于我,因为我得到了uncaughttypeerror:无法将未定义(匿名函数)的属性“bind”作为错误读取 Javascript对我

我正在努力教自己制作一个游戏的画布

所以我让一切都正常工作,并决定给我的游戏赋予它自己的对象(我已经有了玩家对象,等等)。我有一大堆被注释掉的东西,稍后我会修复。但我现在不能让皇家空军去工作。我在谷歌搜索并修复了
requestAnimationFrame(this.animate)
时遇到的第一个错误。但是这个Function.prototyping.bind不适用于我,因为我得到了
uncaughttypeerror:无法将未定义(匿名函数)
的属性“bind”作为错误读取

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
正在调用一个匿名函数,您可以在其中引用此。但是,在匿名函数中,
将是
窗口
(或未定义),因此没有
此。动画
,因此无法进行属性绑定

将这些变量定义为
设置超时
之外的变量,这样您就可以在不使用
的情况下访问它们,或者设置
var foo=this
并以
foo.animate
等方式访问所有内容。您似乎已经在使用
那个
变量执行此操作,但没有使用它


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

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);
}

您可以从函数表达式创建
bind\u render
,但是我觉得分离
bind
步骤可以提高可读性。与
anim_loop
类似,它可以作为一个命名函数表达式直接传递到setTimeout

中,为什么要将
setTimeout
requestAnimationFrame
混合使用???这是完全相同的错误,具有完全相同的解决方案在那里做,你打算在什么地方使用它(为什么)?提示:
raf(that.animate.bind(that))
@Bergi看起来像是OP想要使用
requestAnimationFrame
进行渲染,并
setTimeout
强制执行某种最大帧速率