0

My question is related to this post, but I am still having problems.

If I have two numbers inside a namespace

var global_namespace = {a:3, b:5};

and the rest of my code is

function change() {
    var a = this.global_namespace.a;
    var b = this.global_namespace.b;

    a += 2;
    b *= 2;
}

console.log(global_namespace.a + " " + global_namespace.b);
change();
console.log(global_namespace.a + " " + global_namespace.b);

I want to declare a reference to the vars in the namespace, but as I watch the debugger, the local a and b vars change without updating the vars in the namespace. The whole reason I am trying to make a reference to the global namespace vars is to allow the use of shorter var names throughout a function to improve readibility. I cannot sacrifice potentially doubling my memory by storing a copy of the namespace inside the scope of the function though.

Community
  • 1
  • 1
Josh Bradley
  • 4,630
  • 13
  • 54
  • 79
  • 2
    Why would you expect the global vars to get updated? You used `var` which creates a local variable in the current lexical scope. You'd have to increment like `global_namespace.a += 2` – elclanrs Jun 26 '14 at 21:00
  • 3
    var `a` and `b` is just a number, it's not passed by reference. – adeneo Jun 26 '14 at 21:02
  • Is there a way to declare a and b as references to the namespace variables? I know incrementing global_namespace.a += 2 works, but I'm trying to get around having to write such long code every time I reference one of the variables (code readibility goes out the window). At the same time, I can't just make a local copy, change it, and then reassign it to the global namespace because I'm worried about doubling the size of memory. – Josh Bradley Jun 26 '14 at 21:13
  • You can make a local copy of "global_namespace": `var gn = global_namespace;` and then `gn.a += 2;` etc. But no, you cannot make a variable be an "alias" for another variable or an object property. – Pointy Jun 26 '14 at 21:18
  • All variables hold a **value**. In the case of assignment of an object (e.g. `var a = {}`), the value is a *reference*. In the case of primitives (e.g. `var b = 3`), the value is the primitive value. So in `var c = a`, the value of *a* is a reference to an object so an equivalent reference is assigned to *c*. In the case of `var d = b`, the value assigned is equivalent to the value of *b* (i.e. `3`). – RobG Jun 26 '14 at 21:39
  • There is only pass-by-value in JavaScript, always, just like Java. However, this is not a question about passing. – newacct Jun 27 '14 at 06:03

1 Answers1

0

If you want change variable by reference you should do

var global_namespace = {a:3, b:5};

function change() {
    global_namespace.a += 2;
    global_namespace.b *= 2;
}

console.log(global_namespace.a + " " + global_namespace.b);
change();
console.log(global_namespace.a + " " + global_namespace.b);
Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47