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?
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 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With