【问题标题】:Why does this throw a Uncaught TypeError: Illegal invocation为什么这会引发 Uncaught TypeError: Illegal invocation
【发布时间】:2015-01-19 03:57:07
【问题描述】:

为什么会抛出“Uncaught TypeError: Illegal invocation”?

function Game () {
    this.reqAnimFrame = window.requestAnimationFrame;

    this.gameLoop = function () {
        this.reqAnimFrame(this.gameLoop); // It's thrown on this line
    };
}

var game = new Game();
game.gameLoop();

【问题讨论】:

  • 这是一种方法,所以在 this.gameLoop 之后需要()

标签: javascript web typeerror


【解决方案1】:

当您调用this.reqAnimFrame 时,window.requestAnimationFrame 的上下文不再是window,而是变为this 的任何内容(在本例中,是Game 的一个实例)。除非您使用正确的上下文调用它们,否则大多数内置函数都不起作用。 (例如,像

var func = console.log; func("blah");

由于同样的原因,效果不佳)。

要解决此问题,您应该只使用原始表单:window.requestAnimationFrame,或者您可以在存储时将其绑定到正确的上下文:

this.reqAnimFrame = window.requestAnimationFrame.bind(window);

【讨论】:

  • 我希望它在函数中而不是在窗口中运行,这就是我制作它的原因,但是谢谢我可以打电话给this.reqAnimFrame(this.gameLoop.apply(this));
  • @Hendry 我想你的意思是this.reqAnimFrame(this.gameLoop.bind(this))
  • 是的!谢谢!这比我以前的效果好得多!
猜你喜欢
  • 1970-01-01
  • 2021-04-09
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多