【问题标题】:CommonJS Illegal invocation error when calling function on module.exports在 module.exports 上调用函数时出现 CommonJS 非法调用错误
【发布时间】:2015-02-14 14:49:07
【问题描述】:

这样做效果很好:

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 commonjs webpack method-invocation


    【解决方案1】:

    我在这里找到了答案:Why are certain function calls termed "illegal invocations" in JavaScript?

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多