admin管理员组文章数量:1289910
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.
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.
Share Improve this question asked Oct 31, 2013 at 13:10 mipmapmipmap 2211 silver badge14 bronze badges3 Answers
Reset to default 11Usual approach, works everywhere:
World.prototype.update = function()
{
var self = this;
requestAnimationFrame(function(){self.update()});
}
Or with ES5 Function.prototype.bind
(patibility):
World.prototype.update = function()
{
requestAnimationFrame(this.update.bind(this)});
}
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.
Game.world.update.call(scope);
Where scope is whatever scope you want to pass in.
https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call#Description
本文标签: javascriptrequestAnimationFrame scope change to windowStack Overflow
版权声明:本文标题:javascript - requestAnimationFrame scope change to window - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741444046a2379088.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论