Given the following code that declares a file-scope variable using the var
keyword:
// File a.js
var foo = "Hello, foo!"; // I know I can remove 'var', but that's not what I'm asking
logVar("foo");
function logVar(name) {
var text = global[name]; // 'global' does not work to access 'foo'!!!
console.log(text);
}
I would like to know how to access the file-scope variable foo
using array notation (i.e., given the text of the variable name - something like global["foo"]
, which as noted does not work).
I have just spent about an hour searching for this; i.e. here, here, or here. Apparently, by using the var foo = ...
syntax at file scope (rather than just foo = ...
), the variable does not appear in global
scope, but rather in the scope of the closure for the file that Node creates to wrap the file.
Now, I know I could just remove the var
from the variable declaration. But that's not what I'm asking.
I'd like to know if it is possible to access file-scope variables declared with var
using array notation given a text string representing the variable name.
Is this possible with Node? If so, how?