Assign an object or an array in javascript does not make a copy. When you do
var B = A;
you now simply have two variables pointing at the exact same object. If you modify that object (through either variable), there is only one object so both reference to that object will see the change.
If you want to copy an object in javascript, you can make a shallow copy by simply just copying all the properties from one object to another:
function shallowCopy(obj) {
var newObj = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
newObj[prop] = obj[prop];
}
}
return newObj;
}
Note, this is a shallow copy. If properties themselves contain other objects, then this won't make new copies of those (it will just copy the reference to them).
With a little more work, you can also do a deep copy where it will make copies of objects contained within the object. The only gotcha for this function is you have to make sure that there are no circular references where A
contains a property which contains an object or array which also contains A
because this will infinite loop if there is a circular reference.
function deepCopy(obj) {
if (typeof obj !== "object" || obj === null) {
return obj;
}
var newObj = obj instanceof Array ? [] : {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
newObj[prop] = deepCopy(obj[prop]);
}
}
return newObj;
}
This function doesn't preserve object types that aren't plain objects (of course, your JSON solution doesn't either). To do that requires even more work involving the constructor.