On several cloning (clone) methods in JavaScript

Source: Internet
Author: User

Clone is to copy the original thing as it is, and the new copy has nothing to do with the previous thing.

A: In JavaScript, if the cloned object is a basic type, we can assign it directly:

var sStr = "Kingwell";   var cStr = sStr;   alert (CSTR); // Output Kingwell   SSTR = "abc";  alert (CSTR); //

When you assign a value to another variable, the value of that variable is not affected when it is changed.

It is important to note that the copy will copy the value of the A object to B, because it is the basic type, this value no longer points to other places, so when the value of a changes, the value of B will not change, but if the assignment is the object, the case is different, although the value of a is copied to B, but this value points to the The real content is stored in the heap memory, so when a object changes the content, the content of the B point changes.

Two: If it's not the basic type, it's all different:

var aarr = [0,1,2,3];   var m = aarrr;  Alert (m); // Output   aarr=[1,1,2,3];  Alert (m); // output 1,1,2,3; This value is changed because M is only a reference to Aarr, and if the value of Aarr is changed, then M will change accordingly.  

If we want to clone an array, the simplest way:

var aarr = [0,1,2,3];   var m = aarr.slice (0);   = [3,2,1,0];  Alert (m); //

We can create a function to clone all objects:

functionClone (obj) {varo; if(typeofobj = = "Object") {          if(obj = = =NULL) {o=NULL; } Else {              if(objinstanceofArray) {o= [];  for(vari = 0, len = obj.length; i < Len; i++) {O.push (Clone (Obj[i))); }              } Else{o= {};  for(varJinchobj) {O[j]=Clone (Obj[j]); }              }          }      } Else{o=obj; }      returno; }  

Three: node cloning:

var p = document.getelementsbytagname ("P") [0];   var cP = P.clonenode (); // clone p node   var cP = P.clonenode (true); // clone p node, deep clone, clone node and sub-content under node.  

On several cloning (clone) methods 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.