gpt4 book ai didi

javascript - 无法读取 null 的属性 ____

转载 作者:行者123 更新时间:2023-11-28 17:40:45 26 4
gpt4 key购买 nike

作为练习,我经历了 this tutorial ,然后尝试创建一个版本,将所有内容放入自己的类中以对其进行清理,以便我可以添加一些自己的添加内容。问题是我遇到了一个似乎没有任何意义的错误。 (所有评论的内容都是我填写的,但似乎与问题无关)Uncaught TypeError: Cannot read property 'lastRender' of null at loop (game-loop.js:13)

class GameLoop {
constructor(player, canvas) {
// Set other variables
this.lastRender = 0;
window.requestAnimationFrame(this.loop);
}

loop(timestamp) {
let progress = timestamp - this.lastRender; // This is ln. 13 in the actual program

this.update(progress);
this.draw();

this.lastRender = timestamp;
window.requestAnimationFrame(this.loop);
}

update(progress) {
// Update function
}

draw() {
// Draw function
}

}

此外,当我从类中删除lastRender变量时,它不再给我这个错误,而是显示Uncaught TypeError: Cannot read property 'update' of null at loop (game-loop.js:15)

最佳答案

您需要使用.bind() 使this 具有正确的值。更改此:

window.requestAnimationFrame(this.loop);

对此:

window.requestAnimationFrame(this.loop.bind(this));

当您像使用 this.loop 那样将方法作为回调传递时,不会传递 this 的值,只会传递对该方法的引用。因此,当 window.requestAnimationFrame() 调用 loop() 时,它的调用方式不会使 this 具有正确的值在方法内部,因此当您尝试使用 this.anything 时,您会看到错误。

关于javascript - 无法读取 null 的属性 ____,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47987307/

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