6

I use the requestAnimationFrame inside a ES6 class such as

 class MyClass{...

     run(){
         requestAnimationFrame(this.animate);
         //also tried requestAnimationFrame(() => this.animate);
     }

     animate(){
        //how to get I back "this" here
     }

I cannot get back the reference to "this" in the callback of the requestAnimationFrame. Any idea how to do this?

Eric
  • 9,870
  • 14
  • 66
  • 102

2 Answers2

15

You have to bind the context either by using an arrow function:

 requestAnimationFrame(() => this.animate());

or by binding the function to the context:

 requestAnimationFrame(this.animate.bind(this));

In newer JavaScript you could also use a class property containing an arrow function:

 class MyClass {
   run(){
     requestAnimationFrame(this.animate);         
   }

   animate = () => {
     //..      
   }
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
3

Jonas W.'s answer is the way to go. You can also bind methods in constructor, like this:

class MyClass {
  constructor() {
    super();
    this.run = this.run.bind(this);
    this.animate = this.animate.bind(this);
  }
}
Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18