爲什麼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