调用module.exports上的函数时发生CommonJS非法调用错误

CommonJS Illegal invocation error when calling function on module.exports

本文关键字:调用 CommonJS 非法 错误 函数 module exports      更新时间:2023-11-10

这样做效果很好:

var requestAnimationFrame = 
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame;
function _test() {
    console.log('hello from test');
}
requestAnimationFrame(_test);

然而,将其移动到另一个文件并使用CommonJS/webpack导出会导致:

Uncaught TypeError: Illegal invocation

(就像这样:)

module.exports.requestAnimationFrame = 
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame;

var poly = require('../utils/polyfills');
poly.requestAnimationFrame(_test);

这可能非常明显,但在我看来,我不明白为什么这不起作用:/

我在这里找到了答案:为什么某些函数调用被称为"非法调用";在JavaScript中?

似乎一些本机函数依赖于上下文,所以为了解决这个问题,我绑定到窗口:

module.exports.requestAnimationFrame = 
    (window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame).bind(window);