Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 691
Autoencoder Debugger Avatar asked Mar 08 '16 21:03

Autoencoder Debugger


1 Answers

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
like image 95
Dustin Hodges Avatar answered Oct 12 '22 21:10

Dustin Hodges