requestAnimationFrame范围更改为窗口

mip*_*map 6 javascript requestanimationframe

我有一个看起来像这样的对象链:

Game.world.update()
Run Code Online (Sandbox Code Playgroud)

我想使用requestAnimationFrame来确定此函数的帧速率.

但是,当我像这样实现它:

World.prototype.update = function()
{
    requestAnimationFrame(this.update);
}
Run Code Online (Sandbox Code Playgroud)

范围从世界对象更改为窗口对象.在调用requestAnimationFrame()时如何维护我想要的范围?我知道它与匿名函数等有关,但我无法理解它.

Jak*_*cil 11

通常的方法,无处不在:

World.prototype.update = function()
{
    var self = this;
    requestAnimationFrame(function(){self.update()});
}
Run Code Online (Sandbox Code Playgroud)

或者使用ES5 Function.prototype.bind(兼容性):

World.prototype.update = function()
{
    requestAnimationFrame(this.update.bind(this)});
}
Run Code Online (Sandbox Code Playgroud)