Object deep cloning in JavaScript

Source: Internet
Author: User
Tags hasownproperty

JavaScript, andNoA method that directly provides object cloning.

The assignment in JavaScript is not actually a copy of the object, but rather a reference (or pointer) in a ' C + + ', so the element in object A is changed when the element in object B is changed in the following code.

A = {k1:1, k2:2, k3:3=4;

If you want to change only B and keep a constant, you need to copy object A.

Object copying with jquery

In the case of jquery, jquery's own extend method can be used to implement object replication.

A = {k1:1, k2:2, k3:3= {};$.extend (b,a);

Custom Clone () method to implement object replication 1. The following method adds a deep clone method to the prototype of object (prototype).

1Object.prototype.clone =function() {2     //Handle null or undefined or function3     if(NULL== This|| "Object"! =typeof  This)4         return  This;5     //Handle The 3 simple types, number and String and Boolean6     if( This instanceofnumber | | This instanceofString | | This instanceofBoolean)7         return  This. ValueOf ();8     //Handle Date9     if( This instanceofDate) {Ten         varcopy =NewDate (); OneCopy.settime ( This. GetTime ()); A         returncopy; -     } -     //Handle Array or Object the     if( This instanceofObject | | This instanceofArray) { -         varcopy = ( This instanceofArray)?[]:{}; -          for(varattrinch  This) { -             if( This. hasOwnProperty (attr)) +COPY[ATTR] = This[attr]? This[Attr].clone (): This[attr]; -         } +         returncopy; A     } at     Throw NewError ("Unable to clone obj! Its type isn ' t supported.); -}

All objects can be used directly with '. Clone () '

var a=[1,2,true,null, "FDSFDSA", [1, "Fdsa", {"A": 1, "B": ["FD", 3,{"B": "3", "C": ""},new date ()], "C":new date (), "D":false, "E":null}]]; var b=a.clone ();
2. Use Extra-Tool function implementation for deep cloning of most objects.

1 functionClone (obj) {2     //Handle The 3 simple types, and null or undefined or function3     if(NULL= = Obj | | "Object"! =typeofObjreturnobj;4 5     //Handle Date6     if(objinstanceofDate) {7         varcopy =NewDate ();8 Copy.settime (Obj.gettime ());9         returncopy;Ten     } One     //Handle Array or Object A     if(objinstanceofArray | ObjinstanceofObject) { -         varcopy = (objinstanceofArray)?[]:{}; -          for(varattrinchobj) { the             if(Obj.hasownproperty (attr)) -COPY[ATTR] =Clone (Obj[attr]); -         } -         returncopy; +     } -     Throw NewError ("Unable to clone obj! Its type isn ' t supported.); +}

Usage is similar to:

var a=[1,2,true,null, "FDSFDSA", [1, "Fdsa", {"A": 1, "B": ["FD", 3,{"B": "3", "C": ""},new date ()], "C":new date (), "D":false, "E":null}]]; var b=clone (a);

Test

The same result can be obtained with both methods.
As for which to use, it depends on your preferences/habits:) As far as I am concerned, I prefer to use the prototype method, convenient, ah hahaha ~
If you want to test the results, directly copy the code to run:

1 vara=[1,2,true,NULL, "Fdsfdsa", [1, "Fdsa", {"A": 1, "B": ["FD", 3,undefined,{"B": "3", "C": ""},NewDate ()], "C":NewDate (), "D":false, "E":NULL, "F":function(){return2;}}],function(){}];2Console.log ("A=", a);3Console.log ("B=a.clone ();");4b=A.clone ();5Console.log ("Json.stringify (a) ==json.stringify (b) =", json.stringify (a) = =json.stringify (b));6Console.log ("Json.stringify (a) ===json.stringify (b) =", json.stringify (a) = = =json.stringify (b));7Console.log ("json.stringify (a) =", Json.stringify (a));8Console.log ("json.stringify (b) =", json.stringify (b));9Console.log ("a[2]=123,b[2]=55555");Tena[2]=123,b[2]=55555; OneConsole.log ("A=", A, "\t\t", "b=", b); A  -Console.log ("B=clone (a);"); -b=Clone (a); theConsole.log ("Json.stringify (a) ==json.stringify (b) =", json.stringify (a) = =json.stringify (b)); -Console.log ("Json.stringify (a) ===json.stringify (b) =", json.stringify (a) = = =json.stringify (b)); -Console.log ("json.stringify (a) =", Json.stringify (a)); -Console.log ("json.stringify (b) =", json.stringify (b)); +Console.log ("a[2]=1234,b[2]=33333"); -a[2]=1234,b[2]=33333; +Console.log ("A=", A, "\t\t", "b=", b);

As you can see, the output ' a ' and ' B ' are equal, but changing the value of the element ' a ' does not affect the ' B ' element.

Object deep cloning in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.