Javascript:使用此调用类中的方法

现在我的代码按预期工作,但我不明白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); 

我希望我能够解释,我的问题。


泛舟湖上清波郎朗
浏览 126回答 1
1回答

MMMHUHU

您传入的回调window.requestAnimationFrame将在不同的上下文中运行,其中this不再是当前对象的实例。作为一种解决方法,您可以通过this.temp.bind(this)或使用箭头函数() => this.temp()。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript