首页 > 代码库 > 深度克隆

深度克隆

浅度克隆表现:

var a="1";

var b=a;
b="2";
console.log(a);// "1"
console.log(b);// "2"
说明:b不会改变a的值
 
为啥要深度克隆?
var arr=[1,2,3,4];
var arr2=arr;
arr2[0]=3;
console.log(arr);//3,2,3,4
console.log(arr);//3,2,3,4
说明:如果arr2数组的第一个数改变,arr也改变了,显然,有的时候,这并不是我们想要的。
 
下面为深度克隆的代码:
 1 function deepClone(obj){ 2     var result,oClass=isClass(obj); 3         //确定result的类型 4     if(oClass==="Object"){ 5         result={}; 6     }else if(oClass==="Array"){ 7         result=[]; 8     }else{ 9         return obj;10     }11     for(key in obj){12         var copy=obj[key];13         if(isClass(copy)=="Object"){14             result[key]=arguments.callee(copy);//递归调用15         }else if(isClass(copy)=="Array"){16             result[key]=arguments.callee(copy);17         }else{18             result[key]=obj[key];19         }20     }21     return result;22 }23 //返回传递给他的任意对象的类24 function isClass(o){25     if(o===null) return "Null";26     if(o===undefined) return "Undefined";27     return Object.prototype.toString.call(o).slice(8,-1);28 }29 var oPerson={30     oName:"rookiebob",31     oAge:"18",32     oAddress:{33         province:"beijing"34     },    35     ofavorite:[36         "swimming",37         {reading:"history book"}38     ],39     skill:function(){40         console.log("bob is coding");41     }42 };43 //深度克隆一个对象44 var oNew=deepClone(oPerson);45  46 oNew.ofavorite[1].reading="picture";47 console.log(oNew.ofavorite[1].reading);//picture48 console.log(oPerson.ofavorite[1].reading);//history book49  50 oNew.oAddress.province="shanghai";51 console.log(oPerson.oAddress.province);//beijing52 console.log(oNew.oAddress.province);//shanghai

 

深度克隆