标签:
JavaScript实现对象的深度克隆
代码实现如下:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>clone</title> 6 7 <script type="text/javascript"> 8 //对象深度克隆方法 9 10 11 //////////给Object添加一个clone()方法,完成深度克隆对象。。。yeahhhhh!!! 12 Object.prototype.clone = function(obj) { 13 14 var o,i,j,k; 15 16 if(typeof(obj)!="object"||obj ===null) //支持string、boolean、number等 17 return obj; 18 19 if(obj instanceof (Array)){ //Array类型 20 o=[]; 21 i=0; 22 j=obj.length; 23 for(;i<j;i++){ 24 if(typeof(obj[i])=="object"&&obj[i]!=null){ 25 o[i]=arguments.callee(obj[i]); //arguments.callee() 调用函数本身,实现递归 26 }else{ 27 o[i]=obj[i]; 28 } 29 } 30 } 31 else{ //最后为Object类型 32 o={}; 33 for(i in obj){ 34 if(typeof(obj[i])=="object"&&obj[i]!=null){ 35 o[i]=arguments.callee(obj[i]); 36 }else{ 37 o[i]=obj[i]; 38 } 39 } 40 } 41 return o; 42 } 43 44 45 var obj1 = { 46 name:"Lee", 47 age:25, 48 49 //obj的son对象属性 50 51 son:{ 52 sname:"john", 53 sage:8, 54 play:function () { 55 return this.sname+" can play basketball!"; 56 }, 57 58 //son 的dog 对象属性 59 dog:{ 60 dogName:"coco", 61 run:function() { 62 return "john‘s dog, "+this.dogName+" can run!"; 63 } 64 } 65 }, 66 sing:function(){ 67 return this.name+" can sing!"; 68 }, 69 }; 70 71 alert(obj1.name); //Lee 72 alert(obj1.son.play()); //john can play basketball! 73 alert(obj1.son.dog.run()); //john‘s dog, coco can run! 74 75 //对象克隆测试: 76 var obj2 = clone(obj1); 77 78 79 alert(obj2.name); //Lee 80 alert(obj2.son.play()); //john can play basketball! 81 alert(obj2.son.dog.run()); //john‘s dog, coco can run! 82 83 </script> 84 </head> 85 <body> 86 <div></div> 87 </body> 88 </html>
同样地,String Boolean number和null 都可以被克隆
测试结果:
1 var str = "abc"; 2 var num = 120; 3 var boo = false; 4 var nu = null; 5 var ss = clone(str); 6 var nn = clone(num); 7 var bb = clone(boo); 8 var nnn = clone(nu); 9 10 alert(ss); //abc 11 alert(nn); //120 12 alert(bb); //false 13 alert(nnn); //null
注意点:typeof() 对Array和Object类型 都返回true 所以这里最好用instanceof
相关测试:
1 var str = "abc"; 2 var num = 120; 3 var boo = false; 4 var nu = null; 5 6 alert(typeof str); //string 7 alert(typeof num); //number 8 alert(typeof boo); //boolean 9 alert(typeof nu); //typeof null = object 10 11 12 13 var arr =[2,3,1];
14 var fun = function(){ 15 return 2; 16 } 17 18 alert(typeof arr); //typeof Array = object
19 alert(arr instanceof Array); //true so instanceof is better than typeof for Array‘s testing 20 alert(arr instanceof Object); //true 21 22 alert(typeof fun); //typeof Function = function
作者:没错high少是我
标签:
原文地址:http://www.cnblogs.com/highshao/p/5440824.html