I haven’t posted for a while as I’ve been busy but I thought I’d post about object cloning because it’s a useful tip and can be used in many situations like browser hacking or general web development. I posted this to the sla.ckers forum a while ago but in case you missed it here goes….
When cloning a object in Javascript many of the examples I found used for(i in..) to traverse the properties and copy each of them. There is a nicer way to do this using the uneval function like this:-
obj={a:1,a:2}
function clone(o) {
return eval(uneval(o));
}
obj2 = clone(obj);
obj2.a=0;
alert(obj.a);
alert(obj2.a);
Giorgio Maone pointed out that it would be nice to prototype the code to make it easier to implement:-
Object.prototype.clone = function() {
return eval(uneval(this));
}
alert("test".clone());
alert((3).clone());
alert(clone.clone());