javascript - In Node.js is there a way to access the variable scope of the parent from a required module? -


for project, have many functions make changes single global variable, since file big, split these functions different modules. however, when passing global variable, creates instance. there way prevent this?

for example, desired output:

var global_var=1;    function first_function(){      console.log(++global_var);  }    function second_function(){      console.log(++global_var);    }    first_function(); //outputs 2  second_function(); //outputs 3  first_function(); //outputs 4

but when trying seperate first_function , second_function different modules,

//in main.js file  var global_var=1;    var first_function=require(./first_function)(global_var);  var second_function=require(./second_function)(global_var);    first_function(); //outputs 2  second_function(); //outputs 2  first_function(); //outputs 2    //in first_function.js , second_function.js  module.exports=function(global_var){        return ++global_var;    }

i don't want reassign or re-transfer global_var everytime want make function calls, since function calls change global_var made thousands of times per minute , global_var object on 1000 keys.

is there way ensure child modules modifying same instance of global object without passing around?

i surprised if code (simplified in example i'm guessing) say. this:

var first_function=require(./first_function)(global_var); 

passes global_var (which isn't global way, it's defined var) in exported function. exported function returns value incremented one. when call it:

first_function(); 

you should error number not function.

there lots of ways solve problem. since variable object, available reference wherever it's used, meaning updating 1 instance should update them all.

solution 1: make first_function.js export function returns function.

//in first_function.js , second_function.js module.exports=function(global_var){   // function value of "first_function"   // when require , pass in "global_var"   return function() {     return ++global_var;   }; }; 

solution 2: use actual global variable.

global.somevar = 1;  // first_function.js module.exports = function() {   return ++global.somevar; }; 

the caveat here global variables typically considered code smell (bad practice).

solution 3: make variable export of file. exports cached, again reference, each file requires variable same reference.

// global_var.js exports.global_var = 1;  // first_function.js var glob = require('./global_var'); module.exports = function() {   return ++glob.global_var; }; 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -