Stas Bichenko
Stas Bichenko

Reputation: 13273

jQuery: object[property].push() modifies old object if the new one is created with jQuery.extend()

Consider this example code:

a={};
a['herp']=['derp'];

var b = jQuery.extend({}, a);
b['herp'].push('foo');
alert(a['herp']); //this produces message box with "derp,foo"

It is my understanding that var b = jQuery.extend({}, a); clones an object (as mentioned by John Resig), i.e. creates a new object with the same properties as the previous. If this is correct, then why does b['herp'].push('foo'); modify a, as indicated by alert(a['herp']);?

jsFiddle example: http://jsfiddle.net/M48tr/

Upvotes: 2

Views: 1030

Answers (2)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

I think you should do:

var b = jQuery.extend(true, {}, a);

Fiddle here http://jsfiddle.net/M48tr/1/

this is because the property is an array and you need a deep clone. As it is written in the documentation:

The merge performed by $.extend() is not recursive by default; if a property of the first object is itself an object or array, it will be completely overwritten by a property with the same key in the second object.The values are not merged.However, by passing true for the first function argument, objects will be recursively merged.

If you don't do a deep copy, b['herp'] just contain a reference to the array that is in a['herp']

Things are different if the properties are not arrays or objects like in this example:

a={};
a['herp']='derp';

var b = jQuery.extend({}, a);
b['herp'] = 'foo';
alert(a['herp']);//alerts derp

alert(b['herp']);//alerts foo

fiddle here http://jsfiddle.net/M48tr/2

Upvotes: 3

Bakudan
Bakudan

Reputation: 19492

You should read more carefully and use google. In general Shallow copy - a new "copy" is created. But points to the same piece of memory(data - variables, constants, etc). Thus representing a "synonym" of the original object. And now the important thing - no matter which one you change, it will affect both.

Deep copy is more time consuming because all of the data of the original object is copied into the new object. The 2 objects have the same structure (rather than pointing to the same). But changes will affect only one of the objects.

Upvotes: 1

Related Questions