现在我的代码按预期工作,但我不明白this这个地方的关键字。当我尝试调用mainLooprequestAnimationFrame 中的方法时,window.requestAnimationFrame(this.mainLoop);它不起作用。当我像在我的例子中那样尝试它时,它起作用了,但我不明白为什么我不能用 调用 mainLoop 方法this,同时能够用this.methodName();.class Game{ constructor(objects){ //some stuff } temp(){ a.mainLoop(); } mainLoop(){ // some other Methods are being called here window.requestAnimationFrame(this.temp); }}var a = new Game(input); 我希望我能够解释,我的问题。
1 回答
![?](http://img1.sycdn.imooc.com/54584ed2000152a202200220-100-100.jpg)
MMMHUHU
TA贡献1834条经验 获得超8个赞
您传入的回调window.requestAnimationFrame
将在不同的上下文中运行,其中this
不再是当前对象的实例。作为一种解决方法,您可以通过this.temp.bind(this)
或使用箭头函数() => this.temp()
。
添加回答
举报
0/150
提交
取消