簡體   English   中英

CommonJS在module.exports上調用函數時出現非法調用錯誤

[英]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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM