ES6类"this"在requestAnimationFrame的回调中? [英] Es6 class "this" in callback of requestAnimationFrame?
本文介绍了ES6类"this"在requestAnimationFrame的回调中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在ES6类(例如
class MyClass{...
run(){
requestAnimationFrame(this.animate);
//also tried requestAnimationFrame(() => this.animate);
}
animate(){
//how to get I back "this" here
}
我无法在requestAnimationFrame的回调中找回对"this"的引用.知道怎么做吗?
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));
在较新的JavaScript中,您还可以使用包含箭头功能的class属性:
In newer JavaScript you could also use a class property containing an arrow function:
class MyClass {
run(){
requestAnimationFrame(this.animate);
}
animate = () => {
//..
}
}
这篇关于ES6类"this"在requestAnimationFrame的回调中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文