Javascript cloning objects

Back to articles

hackvertor

Author:

Gareth Heyes

@hackvertor

Published: Thu, 10 Apr 2008 08:28:43 GMT

Updated: Sat, 22 Mar 2025 15:38:10 GMT

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:-

<pre lang="javascript"> obj={a:1,a:2} function clone(o) { return eval(uneval(o)); } obj2 = clone(obj); obj2.a=0; alert(obj.a); alert(obj2.a); </pre>

Giorgio Maone pointed out that it would be nice to prototype the code to make it easier to implement:-

<pre lang="javascript"> Object.prototype.clone = function() { return eval(uneval(this)); } alert("test".clone()); alert((3).clone()); alert(clone.clone()); </pre>

Back to articles