views:

41

answers:

5

Hello,

I have a global JSON variable where I store some parameters and then each time I run the function I want to be able to modify them but just locally inside that function.

So every time I run the function I want a fresh copy of the global variable inside the local one.

The problem is that I copy the global variable to a local one defined in the function, and I make changes to the local variable, but the next time I run the function, instead having an intact copy of the global variable, I am having the one where I have already modified things.

Thanks! :)

var test = {"name":"me"};
function bla() {
  var t=test;
  t.name="you";
  t.age=55;
  alert(test.name); // Returns "you" that have been set locally instead of "me" that was global value.
}
bla();
+2  A: 

Objects are assigned by reference so after

var t=test;

variables t and test refer to the same object. You need to make a copy of the object to get the behavior you are looking for. Since you are working with JSON, you could just serialize the original object, then re-parse into a new variable

var t = JSON.parse(JSON.stringify(test));

Then modify the new object as you please

MooGoo
Going through JSON to clone an object will blast away any non-serializable members (such as functions).
Victor Nicollet
Read "Since you are working with JSON", then read the title and the body of this question. As long as the object is intended for JSON, serializing and deserializing to clone is likely faster and less error prone than writing a custom recursive function.
MooGoo
+2  A: 

var t = test does not create a copy of the object. It simply references the same object with another name. If you wish to copy the object, consider using something like jQuery's $.extend() function:

var t = $.extend({}, test);

While on that topic, the equivalent code for arrays is the following:

var t = test.slice(0);
Victor Nicollet
+2  A: 

on your line

var t=test;

you're not copying the contents of test, you're creating a new reference to the same content. therefore, any modification to t's content, modifies test as well.

Javier
+1  A: 

To copy an arbitrary object to another variable, use a prototype function like this one:

Object.prototype.clone = function() {
  var newObj = (this instanceof Array) ? [] : {};
  for (i in this) {
    if (i == 'clone') continue;
    if (this[i] && typeof this[i] == "object") {
      newObj[i] = this[i].clone();
    } else newObj[i] = this[i]
  } return newObj;
};

Usage:

var bar = foo.clone();

http://my.opera.com/GreyWyvern/blog/show.dml/1725165

Robert Harvey
+1  A: 

You need to clone the object, so that you can modify the clone and leave the original intact... http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object

Šime Vidas