浅克隆:原始类型按值传递,对象类型按引用传递,与原对象共用一处内存,修改会使原对象也修改
1 var lilei={ 2 sname:"li lei", 3 sage:12, 4 address:{ 5 city:"xian", 6 street:"未央区" 7 } 8 } 9 function clone(oldObj){ 10 if(oldObj==null){return null}; 11 if(typeof oldObj!=="Object"){return oldObj} 12 var newObj = Array.isArray(oldObj)?[]:{}; 13 for(var key in oldObj){ 14 newObj[key] = oldObj[key] 15 } 16 return newObj; 17 } 18 var lilei2 = clone(lilei); 19 console.log(lilei===lilei2)//true 20 console.log(lilei); 21 console.log(lilei2) 22 lilei2.sname="李雷" 23 console.log(lilei.sname);//李雷 24 lilei2.address.city="beijing"; 25 console.log(lilei.address.city);//beijing 很明显原对象的属性值已被修改
深克隆:在内存中开辟一块新内存,将原对象中的所有值全部复制过去,与原对象完全脱离,修改新对象中的属性值不会影响原对象、
1 var hmm={ 2 sname:"han meimei", 3 sage:15, 4 address:{ 5 city:"shenzhen", 6 street:"林湖区" 7 } 8 } 9 function clone2(oldObj){ 10 var newObj = Array.isArray(oldObj)?[]:{}; 11 for(var key in oldObj){ 12 if(typeof oldObj[key] !=="object"){ 13 newObj[key]=oldObj[key] 14 }else{ 15 newObj[key]=clone2(oldObj[key]) 16 } 17 } 18 return newObj; 19 } 20 var hmm2=clone2(hmm); 21 console.log(hmm,hmm2); 22 console.log(hmm===hmm2);//false 23 hmm2.sname="韩梅梅" 24 hmm2.address.city="xian"; 25 console.log(hmm.sname);//还是han meimei 原对象没变 26 console.log(hmm.address.city);//还是shenzhen 原对象没变