Javascript:用这个调用 类 中的方法
Javascript: calling methods in classes with this
现在我的代码可以按预期工作,但我不明白这个地方的关键字 this
。
当我尝试使用 window.requestAnimationFrame(this.mainLoop);
调用 requestAnimationFrame 中的 mainLoop
方法时,它不起作用。
当我像在我的示例中那样尝试它时,它起作用了,但我不明白为什么我不能用 this
调用 mainLoop 方法,同时能够调用中的所有其他方法这个 class 和 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);
我希望我能够解释我的问题。
您传递给 window.requestAnimationFrame
的回调将 运行 在不同的上下文中,其中 this
将不再是您当前对象的实例。
作为解决方法,您可以传递 this.temp.bind(this)
或使用箭头函数 () => this.temp()
.
现在我的代码可以按预期工作,但我不明白这个地方的关键字 this
。
当我尝试使用 window.requestAnimationFrame(this.mainLoop);
调用 requestAnimationFrame 中的 mainLoop
方法时,它不起作用。
当我像在我的示例中那样尝试它时,它起作用了,但我不明白为什么我不能用 this
调用 mainLoop 方法,同时能够调用中的所有其他方法这个 class 和 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);
我希望我能够解释我的问题。
您传递给 window.requestAnimationFrame
的回调将 运行 在不同的上下文中,其中 this
将不再是您当前对象的实例。
作为解决方法,您可以传递 this.temp.bind(this)
或使用箭头函数 () => this.temp()
.