I'm trying to get a function to set a variable at top-level scope of a module, but not have it leak into global scope (because... bad). At first I thought implicit variable declarations in a module would stay in the module, but it seems like it goes to the script calling the module too.
Take for example (aModule.node.js):
var
onlyToThisModule = true;
function createAGlobal() {
//creates a implicit var unfortunately
globalToEveryone = true;
}
createAGlobal(); //this will now appear in the global scope for the script that require() it. eeek.
console.log(onlyToThisModule);
exports = createAGlobal;
Then require it:
var
aModule = require('./aModule.node.js');
console.log(globalToEveryone); //outputs "true"
console.log(typeof onlyToThisModule); //outputs "undefined"
What I would like to do is to declare a variable in createAGlobal
that would not leak into the global scope. I'd like to keep it in the scope of the function that called it. I know I can put it in the var statement of the module itself, but I'm looking to declare the variables only if someone executes the function. Is there a way to achieve this type of scoping?