Why does the function return the value of a local JSON variable instead of a global one?

I have a global JSON variable where I store some parameters, and then every time I run the function, I want to be able to change them, but only locally inside this function.

Therefore, every time I run the function, I want to get a new copy of the global variable inside the local one.

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

Thank!:)

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();
+3
5
+1

,

var t=test;

t test . , , . JSON, ,

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

,

+2

var t = test . . , jQuery $.extend():

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

:

var t = test.slice(0);
+2

var t=test;

test, . t- .

+2

, , :

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;
};

:

var bar = foo.clone();

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

+1

Source: https://habr.com/ru/post/1764931/


All Articles