LJ Wadowski
LJ Wadowski

Reputation: 6720

Access NodeJS module scope variables as object

I can access node global variables as property of GLOBAL object.

can I access module scope variables in similar way?

e.g.

var fns_x = function(){/*...*/};
var fns_y = function(){/*...*/};

function aFn(param){
   /* moduleScope = something that allows me to access module scope variables */
   if(moduleScope['fns_' + param]){
      moduleScope['fns_' + param]();
   }
}

/*...*/
module.exports = /*...*/

Or it's better to wrap those variables in object? e.g.

var fns = {
   x: x = function(){/*...*/},
   y: x = function(){/*...*/}
}

function aFn(param){
   if(fns[param]){
      fns[param]();
   }
}

/*...*/
module.exports = /*...*/

Upvotes: 8

Views: 1751

Answers (1)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38922

Short answer is NO.

Though in the ECMAScript specification variable declarations are available in the Environment Record setup for module, it is specified that this should not be accessible programmatically.

It is impossible for an ECMAScript program to directly access or manipulate such values [spec]

One workaround is to maintain a private variable as container for your functions and expose a lookup function.

var registry = {
   x: function () {},
   y: function () {},
};


module.exports = function (prop) { 
  return registry[prop]; 
};

Note that static analysis of the module code is lost this way.

You can also bind to the global environment but you run the risk of overriding important variables set in the module global scope.

var that = this;

that.x = function () {};
that.y = function () {};

 module.exports = function (prop) { 
    return that[prop]; 
 };

Upvotes: 4

Related Questions