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

CommonJS Illegal invocation error when calling function on module.exports

这样做很好:

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

这可能非常明显,但在我看来我不明白为什么那行不通:/

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

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

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