fileA.js
function addEvent(param1, param2) => {
// do something
})
model.exports = function aFunctionThatUsesAddEvent(param1, param2) {
addEvent(param1, param2) // This works fine.
})
fileB.js
const FileA = require(__dirname + '/..fileA');
function letsAddEvent(param1, param2) {
FileA.addEvent(param1, param2) {
// I get an error: FileA.addEvent is not a function
})
})
我尝试过使用
model.exports = function addEvent(param1, param2) => {})
但是aFunctionThatUsesAddEvent
无法调用addEvent(param1, param2)
如何声明一个可以在本地使用并且也被另一个文件使用的函数?
答案 0 :(得分:2)
fileA.js
function addEvent(param1, param2) => {
// do something
})
function aFunctionThatUsesAddEvent(param1, param2) {
addEvent(param1, param2)
})
module.exports.aFunctionThatUsesAddEvent = aFunctionThatUsesAddEvent
FileB.js
const FileA = require(__dirname + './fileA'); // Not sure where are you importing the file form
function letsAddEvent(param1, param2) {
FileA.aFunctionThatUsesAddEvent(param1, param2) {
// your code
})
})
答案 1 :(得分:2)
您要从function aFunctionThatUsesAddEvent
导出fileA.js
。
因此,当您在const FileA = require(__dirname + '/..fileA');
中致电fileB.js
时,FileA
变为function aFunctionThatUsesAddEvent
且FileA
没有任何addEvent
。
这个问题有多种解决方案。
最简单的一个:
<强> fileA.js 强>
function addEvent(param1, param2) => {
// do something
})
function aFunctionThatUsesAddEvent(param1, param2) {
addEvent(param1, param2)
})
modules.exports = {
addEvent: addEvent,
aFunctionThatUsesAddEvent: aFunctionThatUsesAddEvent
}
<强> fileB.js 强>
const FileA = require(__dirname + '../fileA');
FileA.addEvent(); // it should work
FileA.aFunctionThatUsesAddEvent() // it should work