[thelist] JS Object Cloning

Erik gozz at gozz.com
Tue Mar 27 15:53:15 CST 2001


No clone() function I know of, but you can do something like this:

var originalArray = new Array('a','b','c');

function Clone(original) {
     for (i in original) {
         this[i] = original[i];
     }
}

var clonedArray = new Clone(originalArray);

clonedArray[1] = prompt('Changed second item to:','(enter my new value here)');

<watchwrap>
alert('Original array: ' + originalArray[0] + ',' + originalArray[1] 
+ ',' + originalArray[2] + '\nCopy of array: ' + clonedArray[0] + ',' 
+ clonedArray[1] + ',' + clonedArray[2]);
</watchwrap>


>I am trying to code some JS so that I can make changes to a data structure
>then commit them later.  My idea was to copy a segment from the structure
>for the dialog to edit, then reinsert the changes if the user clicks same.
>But, the problem is that when I try to copy the section to a temporary
>place, I'm copying pointers, not clones of the data.
>
>So, I made it automatically reconstruct the data structure on the fly using
>a bunch of new Array(), but as I copy the leaves over, again, I'm getting
>pointers.
>
>Is there a clone() method?  If not, how can I make one?
>
>Thanks in advance.
>
>-joshua
>
>
>---------------------------------------
>For unsubscribe and other options, including
>the Tip Harvester and archive of TheList go to:
>http://lists.evolt.org Workers of the Web, evolt !

-- 
- Erik Mattheis

http://gozz.com/
(612) 827 3963




More information about the thelist mailing list