gpt4 book ai didi

Javascript:用 this 调用类中的方法

转载 作者:行者123 更新时间:2023-11-28 03:28:52 25 4
gpt4 key购买 nike

现在我的代码按预期工作,但我不理解关键字 this在这一处。当我尝试调用mainLoop时requestAnimationFrame 中的方法 window.requestAnimationFrame(this.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);

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

最佳答案

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

关于Javascript:用 this 调用类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58357794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com