Javascript:在文件之间共享功能

时间:2018-02-16 05:27:02

标签: javascript node.js function

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)

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

2 个答案:

答案 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 aFunctionThatUsesAddEventFileA没有任何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