如何在模块导出中使用全局函数?
How to use global function in module exports?
如何在导出函数中使用全局函数?
示例:
index.js
const another = require('./another');
let myfunc = msg => console.log(msg);
another("Hello World!"); // This gives me myfunc is not defined
another.js
module.exports = msg => myfunc(msg); // myfunc is a "global" function
我需要这样做,因为 another.js 中的代码是递归的,我在 index.js
中经常使用它
在您的 another.js 中,您应该更改为
module.exports = (msg, callback) => callback(msg);
然后,在您的 index.js 中,您更改为
const another = require('./another');
let myfunc = msg => console.log(msg);
another("Hello World!", myfunc);
它现在应该可以工作并在控制台上打印。这是nodejs中的常见模式
如何在导出函数中使用全局函数?
示例:
index.js
const another = require('./another');
let myfunc = msg => console.log(msg);
another("Hello World!"); // This gives me myfunc is not defined
another.js
module.exports = msg => myfunc(msg); // myfunc is a "global" function
我需要这样做,因为 another.js 中的代码是递归的,我在 index.js
中经常使用它在您的 another.js 中,您应该更改为
module.exports = (msg, callback) => callback(msg);
然后,在您的 index.js 中,您更改为
const another = require('./another');
let myfunc = msg => console.log(msg);
another("Hello World!", myfunc);
它现在应该可以工作并在控制台上打印。这是nodejs中的常见模式