无法读取属性____的null [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

作为练习,我通过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)

javascript object methods null es6-class
1个回答
3
投票

你将需要使用.bind()使this具有正确的价值。改变这个:

window.requestAnimationFrame(this.loop);

对此:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.