View Full Version : Clone Native Javascript Object

05-08-2009, 09:25 PM
So what I want to do is clone the Object String and be able to use the clone. In essence what I'm looking to do:

var x = 'me';
String.prototype.returnMe=function(){return this;}
alert(x.returnMe(x)); // alerts: me

// What I want to do:
var String2 = String.clone();

// Reason Why I want to do this/What I hope to be able to do:
String.prototype.returnMe=function(){return this+'2';}
alert(x.returnMe(x)); // alerts: me2
alert(String2.x.returnMe(x)); // alerts: me

Is this possible? And if so, how? I've looked forever to clone objects and such, but nothing ever talks about how to clone a native object and be able to use that object.

P.S. This is the code I tried to clone an object that didn't work (or I just typed the above code incorrectly in order to get the right results):

Object.prototype.clone = function() {
var newObj = (this instanceof Array) ? [] : {};
for (i in this) {
if (i == 'clone') continue;
if (this[i] && typeof this[i] == "object") {
newObj[i] = this[i].clone();
} else newObj[i] = this[i]
} return newObj;

05-08-2009, 09:37 PM
Not sure if this will help, but we had an interesting discussion (http://www.google.com/url?sa=t&source=web&ct=res&cd=23&url=http%3A%2F%2Fwww.codingforums.com%2Fshowthread.php%3Ft%3D2902%26pp%3D15%26highlight%3Dcopy%2Bobj ect&ei=24gESuOlJqPmsgPDg5zgAQ&rct=j&q=+site%3Awww.codingforums.com+codingforums.com+copy+object+adios&usg=AFQjCNFXWB-HWxqkEF2oKtaduA5oi8_P9w) of a similar issue here about a hundred years ago.

Warning: the archive here is acting weirdly, so prepare to bail on it ...

05-08-2009, 09:53 PM
@adios It helped me a little, but I still don't fully understand it. From what I understood, you can't copy a method of a native object in IE (I'm assuming IE6 and below) and have it work because there may potentially be code in that method that does not allow you to replicate that method properly.

The problem with this is that I am creating a new method within String and thus know that the code within String does not depend on anything but what is passed into it. So shouldn't I be able to copy String in this instance?

And I'm also assuming that Javascript has changed a little since 2002 (not to mention the new browsers that have become normal since then [IE7, FF2/3] that now have different renderers).

Any additional help would be greatly appreciated.

05-08-2009, 10:25 PM
There's no need to clone primitive data types (ie numbers and strings in JS). Primitive data type variables don't pass references on assignation, they pass the actual value.


// primitive data types
var str1 = "hey";
var str2 = str1;
str2 += "2";
alert("str1 = "+str1+"\nstr2 = "+str2);

var num1 = 10;
var num2 = num1;
num2 += 5;
alert("num1 = "+num1+"\nnum2 = "+num2);

var obj1 = {data:"hey"};
var obj2 = obj1;
obj2.data += "2";
alert("obj1.data = "+obj1.data+"\nobj2.data = "+obj2.data);

var arr1 = [10];
var arr2 = arr1;
arr2[0] += 5;
alert("arr1[0] = "+arr1[0]+"\narr2[0] = "+arr2[0]);

05-08-2009, 11:45 PM
@itsallkizza For my example I used primitive data types in order to show display my point in a simple manner, but the prototypes I am adding are generally much more complicated than that. Thanks for the info though!

05-10-2009, 08:41 AM
Here I wrote this up for you. I may have left something out but it should clone any JS object/data type. See the window.onload for an example.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
// <![CDATA[

function clone(o)
if (typeof(o) == "string" || typeof(o) == "number" || typeof(o) == "function") return o;
if (typeof(o) == "function") return new Function(o.toString());
if (o.constructor.toString().indexOf("Array") != -1)
var new_o = new Array();
for (var i=0;i<o.length;i++) new_o[i] = clone(o[i]);
return new_o;
var new_o = new Object();
for (var k in o) new_o[k] = clone(o[k]);
return new_o;

var my_obj = {
arr:["ten thousand",10000,{str:"hey from inside array",arr:[1,2,3]}],
obj:{str:"hey from inside obj",num:0},
func: new Function("alert('hey!');")

window.onload = function()
var my_obj_referenced = my_obj;
var my_obj_cloned = clone(my_obj);

my_obj.arr[2].str = "changed my str inside array";
my_obj.func = function(){alert("goodbye!")};

//test changes
document.getElementsByTagName("body")[0].innerHTML += my_obj_referenced.arr[2].str;
document.getElementsByTagName("body")[0].innerHTML += "<br />"+my_obj_cloned.arr[2].str;

// ]]>