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, $.extend
merely 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.
var shat = [{bang:true}, {bumm: false}, {bong: false}]
var shot = [{bang:false}, {bumm: false}, {bong: false}]
$.extend(true, shat, shot) // use "deep copy"
shat[0] === shot[0] // false; different objects now so...
shot[0].bang = "boom" // ...this will not affect the object named by shat[0]
shot[0].bang // "boom"
shat[0].bang // false
Happy coding.
*That is, for every property, p
, in the source object(s), it merely does target[p] = source[p]
. Remember that, in JavaScript, Arrays are just a special subtype of object with a magical length
: the value at index n is named by the property "n".