0

Possible Duplicate:
Is JavaScript a pass-by-reference or pass-by-value language?

In this file I have an object this.objectA and this.allAs; this.objectA contains a few attributes. Everytime I got a new this.objectA, I add it to the array this.allAs. I always reassign this.objectA when I get a new one.

Later I check my array this.allAs, I found that it correctly stores different this.objectA. How come this.objectA gets overwritten, the objects inside this.allAs didn't get overwritten? (I expect all those stored objects to to pointing to the same this.objectA, but it didn't) Javascript is pass by value for objects???

Community
  • 1
  • 1
yeeen
  • 4,911
  • 11
  • 52
  • 73

1 Answers1

0

You've got to get a lot more specific about what you're doing. JavaScript passes by reference, but if you're saving local copies anywhere, and copying those values from return statements, then you're not working from reference anymore -- they're no longer pointers to the exact same object, necessarily.

Here's something to demonstrate passing references:

Bob = { name : "Bob", age : 32 };
function giveBobTo (obj, bobject) { obj.bob = bobject; }

Billy = {};
Jim = {};

giveBobTo(Billy, Bob);
giveBobTo(Jim, Bob);

Jim.bob.cars_on_lawn = 8;
Billy.bob.cars_on_lawn;  // 8;
Bob.cars_on_lawn;        // 8;

console.log( "Billy-Bob equals Jim-Bob equals Bob:",
             Billy.bob === Jim.bob === Bob); // true
Norguard
  • 26,167
  • 5
  • 41
  • 49
  • 2
    Javascript passes by value. Some values are primitives, others are object references so some say it passes primitives by value and objects by reference, which is more–or–less correct. – RobG Jul 23 '12 at 05:04
  • Yes, that's pretty much it. Of course, it always ends up being more complex than that, if you're, say, recursively traversing some node-path and need to keep track of what you're assigning where. Cloning objects' values becomes increasingly more difficult the deeper the objects are nested. Recursion can simplify that a great deal, but stacks only go so far. Assignment of primitives to variables/objects/array-indices is by value. But even if you were to pass in a primitive variable and edit that variable in-place in the function, that would be by-reference (primitives as objects). – Norguard Jul 23 '12 at 05:44
  • —I don't get `But even if you were to pass in a primitive variable and edit that variable in-place in the function, that would be by-reference (primitives as objects)`. Primitives are only temporarily converted to objects where required to evaluate an expression, the change is not permanent (e.g. in `x='string';x.split();` the value of `x` is coerced to a String object only to evaluate the expression, its value remains a primitive string. – RobG Jul 23 '12 at 06:01