Why does this throw a Uncaught TypeError: Illegal invocation

Why does this throw a Uncaught TypeError: Illegal invocation

为什么会抛出 "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.reqAnimFrame 时,window.requestAnimationFrame 的上下文不再是 window,而是成为 this 的任何内容(在这种情况下,Game).除非您在正确的上下文中调用它们,否则大多数内置函数都不起作用。 (例如,

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

效果不佳,原因相同。

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

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