2015-03-02 47 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的上下文。

相關問題