8

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 = /*...*/
2
  • 2
    Why not just export fns (modify the 2nd example a little)? I don't see the need for the function that checks if the functions have been declared. Commented Apr 25, 2016 at 10:22
  • Just encountered the same problem - want to read a directory and require all of it's files as a variables at module scope, but I don't want to wrap them. Commented Sep 9, 2017 at 13:09

1 Answer 1

4

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]; 
 };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.