Es6类"this"在requestAnimationFrame的回调中?

Eri*_*ric 1 javascript ecmascript-6

我在ES6类中使用requestAnimationFrame,例如

 class MyClass{...

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

     animate(){
        //how to get I back "this" here
     }
Run Code Online (Sandbox Code Playgroud)

我无法在requestAnimationFrame的回调中找回对"this"的引用.知道怎么做吗?

Jon*_*lms 6

 requestAnimationFrame(() => this.animate());
Run Code Online (Sandbox Code Playgroud)

要么

 requestAnimationFrame(this.animate.bind(this));
Run Code Online (Sandbox Code Playgroud)

在js的未来版本(目前是第3阶段)中,您可以:

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

   animate = () => {
     //..      
   }
}
Run Code Online (Sandbox Code Playgroud)