为什么这会引发未捕获的类型错误:非法调用

Why does this throw a Uncaught TypeError: Illegal invocation

本文关键字:类型 错误 调用 非法 为什么      更新时间:2023-09-26

为什么会抛出"未捕获的类型错误:非法调用"?

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);