Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  144] [ 6]  / answers: 1 / hits: 46107  / 12 Years ago, tue, december 18, 2012, 12:00:00

On page load I am creating two Javascript Objects, objDemo1 and objDemo1Backup where the latter is simply an exact copy of the first.



e.g.



objDemo1 { 
sub_1 = { something: 123, somethingElse: 321 },
sub_2 = { something: 456, somethingElse: 654 }
}


I can modify the values in sub_ as well as add / delete new sub_'s but the only object I am editing is objDemo1. i.e. I never change objDemo1Backup



I have a reset button that when clicked will reset objDemo1 back to what it was when the page originally loaded (i.e. objDemo1 = objDemo1Backup). This is where I am having the issue..



How do I set objDemo1 to objDemo1Backup?



I have tried:



objDemo1 = objDemo1Backup;


and



objDemo1 = null;
var objDemo1 = objDemo1Backup;


...as well as similar variations but nothing seems to work.
Any ideas?




  • Note: I can confirm that at the point of resetting, objDemo1Backup is exactly the same as it was when I created it and objDemo1 has changed.

  • My code is definetly hitting the reset functionality, where I've tried the objDemo1 = objDemo1Backup... I just cannot figure out the syntax to replace the object.


More From » reset

 Answers
9

In JavaScript objects are passed by reference, never by value. So:



var objDemo, objDemoBackup;
objDemo = {
sub_1: foo;
};
objDemoBackup = objDemo;
objDemo.sub_2 = bar;
console.log(objDemoBackup.sub_2); // bar


To get a copy, you must use a copy function. JavaScript doesn't have one natively but here is a clone implementation: How do I correctly clone a JavaScript object?



var objDemo, objDemoBackup;
objDemo = {
sub_1: foo;
};
objDemoBackup = clone(objDemo);
objDemo.sub_2 = bar;
console.log(objDemoBackup.sub_2); // undefined

[#81352] Monday, December 17, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maurodannyr

Total Points: 126
Total Questions: 103
Total Answers: 105

Location: Maldives
Member since Sun, Feb 27, 2022
2 Years ago
;