4

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?

0

3 Answers 3

4

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

Source and further reading:

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Actually, strings are immutable in js. Therefore, you are always passing them by reference. All operations on strings return a new string.
In JavaScript, when you pass an object, you are really passing an object reference by value. See this earlier question.
1

JavaScript is pass by value, as has been clarified in an earlier question. (Someone with more powers should mark this as duplicate--the answers here are incorrect.)

Comments

0

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

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.