CommonJS在module.exports上调用函数时出现非法调用错误

时间:2015-02-14 14:49:08

标签: javascript commonjs webpack method-invocation

这样做很好:

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

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

1 个答案:

答案 0 :(得分:0)

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

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

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