javascript - requestAnimationFrame回调中的es6类 "this"?

标签 javascript ecmascript-6

<分区>

我在 ES6 类中使用 requestAnimationFrame,例如

 class MyClass{...

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

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

我无法在 requestAnimationFrame 的回调中取回对“this”的引用。知道如何做到这一点吗?

最佳答案

您必须使用箭头函数绑定(bind)上下文:

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

或者通过将函数绑定(bind)到上下文:

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

在较新的 JavaScript 中,您还可以使用包含箭头函数的类属性:

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

   animate = () => {
     //..      
   }
}

关于javascript - requestAnimationFrame回调中的es6类 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49197700/

相关文章:

javascript - JavaScript 可以判断 Firefox 中是否启用了跟踪保护吗?

javascript - 动态添加 iframe 时不需要的页面重新加载

ecmascript-6 - 绑定(bind)函数是否支持 ES6 中的正确尾调用?

javascript - AngularJS - 语法错误 : Unexpected token '>' error in Safari Browser

javascript - 为什么我的 Blast wow slider 有一个白色背景,覆盖了 google chrome 页面的一半?

javascript - 当鼠标悬停在表格上时,复选框会向左移动

javascript - 改变第二轮setInterval的速度

javascript - ES6 : Public Symbols vs Private Symbols

javascript - 使用 MethodDecorator 更改函数的参数,而不更改 "this value"?

typescript - 将 TypeScript 编译为多个目标