简体   繁体   中英

nodejs function declaration

I am declaring a function like so in a file:

File1:
    module.exports = {
       function1: function(callback){
          //do some work
       },
    }

In another file if i import File1 and call file1.function1 the function runs and I get the result.

Although, if I am in File1 and declare another function:

module.exports = {
    function1: function(callback){
          //do some work
    },
    function2: function(callback){
        var result = function1...
    }
}

In this case I am getting function1 is not defined.

Why is this happening? shouldn't it be called the someway independent of where the call is being made?

The problem is that you are trying to access function1 from the wrong scope. There is no defined "function1" variable in your scope. You only have module.exports.function1

const exportObject = {
    function1: function(callback){
          //do some work
    },
    function2: function(callback){
        var result = exportObject.function1... // or this.function1
    }
}

module.exports = exportObject;

Should work

UPDATE: a few more examples:

function1() {
   // this will be executed by example2
}

var example3 = {
   function1: function () {
      // this will be executed by example3
   }
}
const exportObject = {
    function1: function(callback){
        // This will be executed by example1
    },
    function2: function(callback){
        // example1
        var result = exportObject.function1() // or this.function1()
        // example2
        var result = function1()
        // example3
        var result = example3.function1()
    }
}

module.exports = exportObject;

function1 is not a variable.

It is a property of the object you assigned to module.exports .

Compare to this:

 var foo = { bar: 1 } console.log(bar); 

bar is a property of foo , not a variable in its own right.

You have to treat it as such.

 var foo = { bar: 1 } console.log(foo.bar); 

The same is true of function1 .

You need to access it as object property:

var result = module.exports.function1();

If you create a function module.exports.function1 in File 1, the way you access it in File 1 is by saying module.exports.function1 . It's a bit long winded. Alternatively, you can create it like this in File 1:

 var function1 = function() {...};
 module.exports.function1 = function1;

 function1();

You can continue to use function1 in File 2:

 var file1 = require('./file1');
 file1.function1();

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