Hen*_*dry 1 javascript typeerror web
为什么会抛出"未捕获的TypeError:非法调用"?
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();
Run Code Online (Sandbox Code Playgroud)
当你调用时this.reqAnimFrame,上下文window.requestAnimationFrame不再是window,而是成为任何东西this(在这种情况下,是一个实例Game).除非使用正确的上下文调用它们,否则大多数内置函数都不起作用.(例如,像
var func = console.log;
func("blah");
由于同样的原因,也不起作用).
要解决此问题,您应该只使用原始表单:window.requestAnimationFrame,或者您可以在存储它时将其绑定到正确的上下文:
this.reqAnimFrame = window.requestAnimationFrame.bind(window);