调用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);
这可能非常明显,但在我看来,我不明白为什么这不起作用:/
我在这里找到了答案:为什么某些函数调用被称为"非法调用";在JavaScript中?
似乎一些本机函数依赖于上下文,所以为了解决这个问题,我绑定到窗口:
module.exports.requestAnimationFrame =
(window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame).bind(window);
相关文章:
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- D3在一个调用中绘制不同的SVG形状,没有可见性
- 如何从Java/scala调用js美化程序
- 如何调用这个匿名 JavaScript 函数
- 如何从模块链中调用函数.导出到节点中
- 我需要从php调用javascript或jquery
- Chrome开发工具(如何知道我在调用哪个javascript对象)
- 单击按钮后如何逐个调用分区,上一个分区将隐藏
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- node.js:setInterval()正在跳过调用
- 如何在单击复选框后调用控制器方法
- 如何在JQuery函数中定义一个值,然后调用另一个函数并使用该值
- 使用Google Visualization动态调用构造函数
- 如何在webView,Android中从@JavascriptInterface方法调用Javascript
- 是否可以将一个函数输入连接到另一个函数调用的文本
- 调用函数内部的函数
- 函数未在Object.keys或Object.getOwnPropertyNames下列出,但可以调用
- 调用module.exports上的函数时发生CommonJS非法调用错误
- 不进行异步调用的CommonJS模块加载程序