简体   繁体   中英

JS - How to access a module.exports function in the same file

I have a function that looks like:

module.exports = myFunction() {
  //do some stuff
}

I can access it fine from other file using var myFunction = require(.thepath.js)

However how can i access it from the file that it was created.

I've tried myFunction() and this.myFunction() but neither work.

Thanks

You can save it to a variable then export the variable like so:

// Create the function
const myFunction = function() {

}

// Call the function
myFunction();

// Export the function
module.exports = myFunction

You could actually use an anonyomous function here if you didn't want to call it in the same file

module.exports = function (){
    // do some stuff
}

As long as you give it a name, you can just call it by using its name.

module.exports = function myFunction(){

// do some stuff }

myFunction()

Sorry, I remembered this incorrectly. There is a scoping problem here that can be solved by defining the function seperately from the assignment.

function myFunction (){
    // do some stuff
}
module.exports = myFunction

myFunction()
var func = module.exports = myFunction(){
   //do some stuff here
}

Now you can access through variable.

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