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?
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?
Share Improve this question edited Mar 8, 2016 at 21:39 Suraj asked Mar 8, 2016 at 21:06 SurajSuraj 3194 silver badges14 bronze badges1 Answer
Reset to default 2Yes 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 ments:
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