Search code examples
javascriptobject-literal

Javascript copy contents of one object literal into another without reflecting changes in future?


I am trying to emulate html5 sessionStorage for browsers which don't support it. I am emulating the sessionStorage object as a object literal, and I am checking to see if it has changed by storing both an old version of the sessionStorage object as well as a new one. However, if I directly make the "old" copy of sessionStorage directly equal to the sessionStorage object itself, if the object sessionStorage gets changed, it will reflect those changes on the "old" copy as well. How do I copy the object literal without it reflecting the changes in the future? An example of the code that is not working is at http://jsfiddle.net/pkXXC/1. Clicking the button will update the sessionStorage object. The results are logged in the console.
Note: You must be using internet explorer 7.0 or below for the example to work.


Solution

  • What you're looking for is called a "deep copy". Google has plenty of examples, and there's one in jQuery - $.extend(true, ...)