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)

如何声明一个可以在本地使用并且还可以被另一个文件使用的函数?

最佳答案

您正在从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

09-25 21:53