Reputation: 13449
I understand how exports works, but how can I create a variable in my main file, and then use that variable in my module? I tried passing my "global" variable to a function in my module, but it passed as a copy, not by reference and since its an array I'm passing that's no good.
For example
# main file
var someObject = {};
var myModule = require('./whatever');
moModule.function_a(someObject);
moModule.function_b(someObject);
Even though someObject is an object it passes by copying, and if I change its value inside function_a or function_b, it wont change in the global scope, or in any other modules where I use it.
Upvotes: 0
Views: 251
Reputation: 18215
If you modify a passed argument, the argument will change outside the function.
However, what you're probably doing that's making you think the object is being copied is you're reassigning the variable.
What you should do:
function foo(a) {
a.bar = 42;
}
var o = {};
foo(o);
console.log(o); // { bar: 42 }
What not to do:
function foo(a) {
a = { bar: 42 };
}
var o = {};
foo(o);
console.log(o); // {}
Upvotes: 3