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:
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With