2015-03-02 80 views
0

为什么window.requestAnimFrame必须如此调用:window.requestAnimFrame(this.__proto__.animate.bind(this));而不是window.requestAnimFrame(this.__proto__.animate);为什么requestAnimFrame需要绑定(this)

我的JS类的样子:

Game = function (moduleConfig, gameConfig) { 
    this.moduleConfig = moduleConfig; 
    this.gameConfig = gameConfig; 

    // Game-Commands 
    this.keyCommands = { 
     moveLeft: false, 
     moveRight: false 
    }; 

    // Some init stuff 

    requestAnimFrame(this.animate.bind(this)); 


    return this; 
} 

/** 
* Init the game system 
* @param {moduleConfig} moduleCongif - Module-Config instance 
*/ 
Game.prototype = { 

    // General member 
    self: null, 
    moduleConfig: null, 
    gameConfig: null, 

    // Game member 
    renderer: null, 
    catcher: null, 
    stage: null, 

    // Nested 'static' objects 
    keyCommands: { 
     moveLeft: false, 
     moveRight: false 
    }, 


    // Some more stuff 

    /** 
    * Main loop 
    */ 
    animate: function() { 
     window.requestAnimFrame(this.__proto__.animate.bind(this)); 

     // Some more things to do 
    } 
} 

如果我不使用bind,我得到以下错误信息:Failed to execute 'requestAnimationFrame' on 'Window': The callback provided as parameter 1 is not a function.

谢谢!

回答

1

因为你的动画是Game的方法,并且由于它是一个递归函数,所以它需要一个上下文才能够调用下一个动画。

现在我已经告诉过你(或者它可能是某人),但.bind使用起来很不方便 - 因为你的主要原因,它非常缓慢,你正在制作一个渲染功能,需要运行速度极快

避免使用绑定的我会做:

animate: function() { 
    var self = this 
    window.requestAnimFrame(function(){ 
     self.animate(); 
    }); 

    // Some more things to do 
} 
+0

好吧,现在我明白了递归函数中的上下文变化。那是我的问题。 – BendEg 2015-03-02 09:46:54

+0

很高兴我能帮到你 – 2015-03-02 09:51:34

1

window.requestAnimFrame可致电window.requestAnimationFrame这将调用参数函数每second.Without“绑定(本)”, '这个。 proto .animate'将调用窗口。 proto .animate.With'bind(this)',它会调用游戏的动画函数,这将是正确的。'bind(this)'只是传递Game的上下文。