0

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.

1
  • Could you post some code of what you did? It should have passed as a reference. Commented Mar 23, 2012 at 2:53

1 Answer 1

3

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); // {}
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.