简体   繁体   中英

Javascript: Sharing a function between files

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
     })
})

I have tried to use

model.exports = function addEvent(param1, param2) => {})

But then aFunctionThatUsesAddEvent can't call addEvent(param1, param2)

How do I declare a function that can be used locally and also used by another file?

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
  })
})

You are exporting function aFunctionThatUsesAddEvent from fileA.js .

So, when you call const FileA = require(__dirname + '/..fileA'); in fileB.js , FileA becomes function aFunctionThatUsesAddEvent and FileA doesn't have any addEvent .

There are multiple solutions to this problem.

Simplest One:

fileA.js

function addEvent(param1, param2) => {
  // do something
})

function aFunctionThatUsesAddEvent(param1, param2) {
    addEvent(param1, param2)  
})

module.exports = {
   addEvent: addEvent,
   aFunctionThatUsesAddEvent: aFunctionThatUsesAddEvent  
}

fileB.js

const FileA = require(__dirname + '../fileA');
FileA.addEvent(); // it should work
FileA.aFunctionThatUsesAddEvent() // it should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM