0

I am facing problem in jQuery that is automatically changes values of variables. Like following example.

 graphB = some values;
 var graphOption = graphB;

Now If I am changing values of "graphOption" then it will automatically changes values of "graphB".

I can not figure out what is the problem.

ParthPatel
  • 114
  • 2
  • 18

3 Answers3

2

Both variables reference the same object, so any changes to its properties made in one gets reflected in the other; you would need to make a (shallow) copy of graphB first:

var graphOption = $.extend({}, graphB);

This creates a new object with copies of the properties from graphB. Note that those copied properties may exhibit the same issue if they reference an object. To avoid that, you would need a deep copy:

var graphOption = $.extend(true, {}, graphB);

See also: jQuery.extend()

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

The problem is not jQuery. In javascript object properties maintain references. In other words, you are not assigning the value, you are making a pointer to the original, if the original is altered the pointer still points to it.

http://snook.ca/archives/javascript/javascript_pass

Javascript pointer/reference craziness. Can someone explain this?

What you need to do is clone the object so you get a copy instead of just a pointer to the original.

You can get around this a number of ways, you can use jQuery's .extend, you can use underscore or lodash's .clone, or angular's .copy or you can do it yourself!

Community
  • 1
  • 1
Fresheyeball
  • 29,567
  • 20
  • 102
  • 164
1

They are both references to the same object. (You can think of the words graphB and graphOption as both just being addresses for an object, not actual objects. They are both pointing at the same place.) To actually duplicate the first, you can use

   var graphOption = $.extend({},graphB);

to make a shallow copy (any internal objects will still use the same references).

or

var graphOption = $.extend(true, {},graphB);

to make a deep copy.

Edit: .clone works on selected dom elements, not objects.

Lola
  • 1,878
  • 1
  • 13
  • 11