views:

79

answers:

2

I have this code

var myObjects = {}; //global variable

//Later on in the code:
for (i in myObjects)
{
    var obj = myObjects[i];
    process(obj);
}

function process(obj)
{
    $.getJSON("example.com/process/", {id: obj.id}, function(result)
      {
          //Will the following change the permanent/global copy e.g 
          // myObjects[44] ?
          obj.addItem(result.id, result.name, result.number);
      }
    );
}

Will the following line:

     obj.addItem(result.id, result.name, result.number);

modify the object by value or by reference, i.e will it modify the local copy of obj or e.g myObjects[44]?

If it affects only the local copy, how can I have it change the global copy of the object?

+3  A: 

Primitive variables are passed by value in JavaScript, but objects are passed by reference.

Source and further reading:

Daniel Vassallo
Note that it's a little weirder than that: if you create a string by calling "new String('hi mom')" then it works kind-of like a string sometimes, but it'll act like an Object for parameter passing. That is, it's passed by reference.
Pointy
Actually, strings are immutable in js. Therefore, you are always passing them by reference. All operations on strings return a new string.
Juan Mendes
A: 

all non-object variables are pass-by-value afaik..

jellyfishtree