I have an array of 20 objects BaseObjects called ArrayBaseObjects.
The user calls an object, it’s loaded in the UI, and he makes changes to the properties.
Something like this:
var ArrayBaseObjects = new Array();
var CurrentObject = null;
function OpenRecord (TheIndex) {
CurrentObject = ArrayBaseObjects[TheIndex];
}
function RecordChanges() {
// bunch of statements that make changes to CurrenObject
CurrentObject.CrazyStuff = NewValue;
}
The problem is that when the user makes changes to the CurrentObject, it also changes the value of the ORIGINAL object in ArrayBaseObjects.
I don’t understand why?? When I write CurrentObject = ArrayBaseObjects[TheIndex]; why does changing CurrentObject also affect the value of the objects in ArrayBaseObject??
I’m looking to compare that value between the orignal object and CurrentObject the user made changes to, but they’re always the same! What changes do I need to make to get this to work the way I intend it?
Thanks for the explanation.
Pretty much everything in JavaScript is passed around by reference. That means unless you explicitly clone an object, assigning the object to a new variable means that now you have two variables pointing to the same object, and changes made to that object through one variable will be visible from the second.
For an answer on how to fix this, what you want is to
clonethe object. However, this isn’t necessarily a trivial thing to perform in an elegant way.Fortunately, JavaScript ninjas out there have already done the hard work. I would suggest using jQuery and it’s excellent
extend()method, which you can specify to do a deep copy. This makes sure that all the data in the object gets cloned, rather than just the top level references.For more information see this question.
In your case, you would use it like so: