简体   繁体   中英

Can function in module.exports access global variable in module?

If I have code like this in one module,

var foo = "bar";

module.exports = function() {
    console.log(foo);
}

and I access it from another like so,

var mod = require('above-module');
mod();

Will it be able to access the variable 'foo' which is local to the module or is it out of scope after 'require' has cached the exported function?

Yes you can do this. Typically questions like this are frowned upon because they can be answered more quickly by just trying it out. You'll get your answer faster that way too

Update based on comments:

Scenario 1 (no errors)

Say you have two modules, module A and module B

module A

var foo = "bar";

module.exports = function() {
    console.log(foo);
}

module B

var mod = require('A');
mod();

If module B is run, "bar" will be logged in the console. If you attempt to access module A's foo directly from another module, you will get errors because foo is out of scope.

Scenario 2 (undefined errors)

If you try to access foo from module A in another module, there will be errors

module C

var mod = require('A');
console.log(foo);  //error.  undefined.  foo is out of scope here
console.log(mod.foo);  //also an undefined error

Scenario 3 (Redefining A to allow foo access outside module)

If you need to have foo accessible outside module A, it needs to be exported. Simplest way to do that would be to add it as a property to the exported function

Redefined module A

var foo = "bar";
module.exports = function() {
    console.log(foo);
}

module.exports.foo = foo;

Then you could access like so

module Accessing foo

var mod = require('A');
var foo = mod.foo;  //access foo in module A like so

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