Changing the requestAnimationFrame application scope

I have a chain of objects that looks like this:

Game.world.update() 

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

However, when I implement it as follows:

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

The area changes from a world object to a window object. How do I save the area I want when calling the requestAnimationFrame () method? I know this has something to do with anonymous functions and the like, but I can't think about it.

+6
source share
3 answers

The 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)}); } 
+11
source
 Game.world.update.call(scope); 

Where scope is the area you want to go to.

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

0
source

Another way to do this is to use a lambda expression like this:

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

It also maintains scope, but a little cleaner.

0
source

Source: https://habr.com/ru/post/957121/


All Articles