0

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?

Community
  • 1
  • 1
Dan Nissenbaum
  • 12,293
  • 18
  • 99
  • 168
  • 2
    I'd say it's not possible. The reason you can do it with the global scope it's because the lexical environment of the global scope is made available as a binding (global scope being a very special thing), but i doubt this is made available for the module scope. – MinusFour May 29 '16 at 14:12

1 Answers1

0

There is a global object in node, aptly named global, but it does not contain variables you declared unless you omit the var keyword. You could declare it as foo = "hello" and access it with global["foo"]. However, be very careful about declaring global variables. If you must have global state, it is better to keep it all inside of one object so that all global variables are in one place and you do not clutter the namespace. For example,

var globalVars = {
    foo: "hello"
};

console.log(globalVars["foo"]);

If you do not do it this way, strange stuff might happen like global["console"].log(). Putting global state inside of one global object is a much more organized approach.

afuous
  • 1,448
  • 10
  • 11