为什么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.
。
谢谢!
好吧,现在我明白了递归函数中的上下文变化。那是我的问题。 – BendEg 2015-03-02 09:46:54
很高兴我能帮到你 – 2015-03-02 09:51:34