2013-10-31 93 views
6

我有對象鏈,看起來像這樣:requestAnimationFrame範圍變更到窗口

Game.world.update() 

我想用requestAnimationFrame以確定此功能的幀率。

然而,當我實現它是這樣的:

World.prototype.update = function() 
{ 
    requestAnimationFrame(this.update); 
} 

從世界對象window對象的範圍變化。 如何在調用requestAnimationFrame()時維護我想要的範圍?我知道它與匿名函數等有關,但我無法理解它。 。

回答

11

慣用的手法,作品無處不在:

World.prototype.update = function() 
{ 
    var self = this; 
    requestAnimationFrame(function(){self.update()}); 
} 

或者與ES5 Function.prototype.bindcompatibility):

World.prototype.update = function() 
{ 
    requestAnimationFrame(this.update.bind(this)}); 
} 
0

這樣做的另一種方式是使用lambda表達式如下所示:

requestAnimationFrame((time) => { loop(time) });

這也維護範圍,但它是一個有點清潔。