Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    New Coder
    Join Date
    Dec 2008
    Posts
    58
    Thanks
    2
    Thanked 1 Time in 1 Post

    Exclamation Clone Native Javascript Object

    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:

    Code:
    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):
    Code:
    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;
    };

  • #2
    Senior Coder
    Join Date
    Jun 2002
    Posts
    1,404
    Thanks
    2
    Thanked 32 Times in 32 Posts
    Not sure if this will help, but we had an interesting discussion of a similar issue here about a hundred years ago.

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

  • #3
    New Coder
    Join Date
    Dec 2008
    Posts
    58
    Thanks
    2
    Thanked 1 Time in 1 Post
    @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.

  • #4
    Senior Coder
    Join Date
    Oct 2008
    Location
    Long Beach
    Posts
    1,196
    Thanks
    36
    Thanked 164 Times in 164 Posts
    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.

    Example:
    Code:
    // 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);
    
    
    //objects
    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]);
    Feel free to e-mail me if I forget to respond ;)
    ohsosexybrit@gmail.com

  • #5
    New Coder
    Join Date
    Dec 2008
    Posts
    58
    Thanks
    2
    Thanked 1 Time in 1 Post
    @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!

  • #6
    Senior Coder
    Join Date
    Oct 2008
    Location
    Long Beach
    Posts
    1,196
    Thanks
    36
    Thanked 164 Times in 164 Posts
    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.
    Code:
    <!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">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Test</title>
    <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 = {
    	str:"hey",
    	num:10,
    	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;
    	my_obj_referenced.func();
    	my_obj_cloned.func();
    	}
    
    // ]]>
    </script>
    </head>
    <body>
    
    </body>
    </html>
    Feel free to e-mail me if I forget to respond ;)
    ohsosexybrit@gmail.com


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •