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

Javascript:使用此函数调用类中的方法,javascript,class,this,Javascript,Class,This,现在我的代码可以正常工作了,但是我不明白这个地方的关键字this。 当我尝试使用窗口.requestAnimationFrame(this.mainLoop)调用requestAnimationFrame中的mainLoop方法时它不工作 当我像在我的示例中那样尝试它时,它起了作用,但我不明白为什么我不能用this调用mainLoop方法,而能用this.methodName()调用这个类中的所有其他方法 class Game{ constructor(objects){ //som

现在我的代码可以正常工作了,但是我不明白这个地方的关键字this。 当我尝试使用
窗口.requestAnimationFrame(this.mainLoop)调用requestAnimationFrame中的
mainLoop
方法时它不工作

当我像在我的示例中那样尝试它时,它起了作用,但我不明白为什么我不能用
this
调用mainLoop方法,而能用
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); 

我希望我能解释我的问题

传递到
窗口的回调。requestAnimationFrame
将在不同的上下文中运行,其中
将不再是当前对象的实例。
作为一种解决方法,您可以传递
this.temp.bind(this)
,或者使用箭头函数
()=>this.temp()
回调,您传递到
窗口。requestAnimationFrame
将在不同的上下文中运行,其中
this
将不再是当前对象的实例。
作为一种解决方法,您可以传递
this.temp.bind(this)
,或者使用arrow函数
()=>this.temp()

如果您没有使用arrow函数或显式地将其与bind()绑定,则此函数的值在处理程序中会发生变化。如果未使用arrow函数或使用bind()显式绑定,则此值在处理程序中会发生更改。