I am extending shat with shot. After extending, why does modifying shot alter shat?
var shat = [{bang:true}, {bumm: false}, {bong: false}]
var shot = [{bang:false}, {bumm: false}, {bong: false}]
$.extend(shat, shot)
shot[0].bang = true
console.log("shat", shat)
// prints
Object
bang: true // why is this true?
Object
bumm: false
Object
bong: false
I am assuming a reference is created or the extending is for some reason happening after the shot[0].bang = true. The problem is, I want to modify shot after the extending, but of course dont want to have it any effect on shat. Any ideas why this is happening and what I could do to avoid that?
see jSfiddle testcase: http://jsfiddle.net/yEnph/3/
By default,
$.extendmerely shallow-copies properties*. It’s not very exciting.In this case, the extended properties are “0”, “1”, “2”, etc, and thus
shat[0] === shot[0]is true after extending which is only the case if both evaluate to the same object. Since they are the same object then … well, mutating it one place mutates it everywhere.To keep them separate consider a “deep copy” (see the different ways to invoked jQuery.extend). Another approach, that I mention because it can also be used in other contexts, is to serialize the object and then de-serialize it — e.g. with JSON.
Happy coding.
*That is, for every property,
p, in the source object(s), it merely doestarget[p] = source[p]. Remember that, in JavaScript, Arrays are just a special subtype of object with a magicallength: the value at index n is named by the property “n”.