开发者

Does javascript handle objects by reference or by value?

I have this code

var myObjects = {}; //global variable

//Later on in the code:
for (i in myObjects)
{
    var o开发者_StackOverflow中文版bj = 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?


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

Source and further reading:

  • JavaScript: Passing by Value or by Reference


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.)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜