requestAnimationFrame scope change to window
Asked Answered
M

3

6

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.

Marlenmarlena answered 31/10, 2013 at 13:10 Comment(0)
M
11

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)});
}
Metamorphosis answered 31/10, 2013 at 13:17 Comment(0)
S
1

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.

Syncopate answered 4/6, 2017 at 17:32 Comment(0)
B
0
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

Bootjack answered 31/10, 2013 at 13:12 Comment(1)
requestAnimationFrame(this.update.call(this)); I tried this, but then I get problems with the stack...Marlenmarlena

© 2022 - 2024 — McMap. All rights reserved.