PDA

View Full Version : Cloning Objects



Trinithis
06-09-2007, 10:32 PM
What would be the best way to clone an object? (I don't want to create a new reference to an object.)

The reason I want to do this is to clone Event objects so I can later reference them instead of the current one using timeouts.

I was thinking around the lines of this:


function clone(o) {
var clone = {};
for(var i in o) {
clone[i] = o[i];
}
return clone;
}

Trinithis
06-09-2007, 10:58 PM
Hmm, but that doesn't work.

Edit: Oh, I need to take out the quotes. Will fix.

Twey
06-10-2007, 12:36 AM
I've a function to do just this in this library (http://www.twey.co.uk/pythonic.js).

Trinithis
06-10-2007, 02:57 AM
Thanks. So it should look something like:


function clone(o, deep) {
var clone = o instanceof Array ? [] : {};
for(var x in o) {
if(deep && typeof o[x]==="object") clone[x] = copy(o[x], true);
else clone[x] = o[x];
}
return clone;
}

Twey
06-10-2007, 01:45 PM
Yep, that looks about right.