requestAnimationFrame scope change to window

泄露秘密 提交于 2019-12-22 05:16:22

问题


I have a chain of objects that looks like this:

Game.world.update()

I would like to use requestAnimationFrame to determine the framerate of this function.

However when I implement it like this:

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

The scope changes from the world object to the window object. How do I maintain the scope I want while calling requestAnimationFrame()? I know it has something to do with anonymous functions and such, but I can't get my head around it.


回答1:


Usual approach, works everywhere:

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

Or with ES5 Function.prototype.bind (compatibility):

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



回答2:


Another way of doing this is to use a lambda expression like so:

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

This also maintains scope but it's a bit cleaner.




回答3:


Game.world.update.call(scope);

Where scope is whatever scope you want to pass in.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call#Description



来源:https://stackoverflow.com/questions/19707443/requestanimationframe-scope-change-to-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!