Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Es6 class "this" in callback of requestAnimationFrame? [duplicate]

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?

like image 339
Eric Avatar asked Mar 09 '18 16:03

Eric


2 Answers

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 = () => {
     //..      
   }
}
like image 100
Jonas Wilms Avatar answered Oct 20 '22 10:10

Jonas Wilms


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);
  }
}
like image 38
Tomasz Bubała Avatar answered Oct 20 '22 11:10

Tomasz Bubała