1 function clone(obj) 2 { 3 if(typeof obj!='object'){ 4 return obj; 5 } 6 7 if(obj instanceof Array){ 8 var arr=[]; 9 for(var i=0; i<obj.length; i++){ 10 arr[i]=clone(obj[i]); 11 } 12 return arr; 13 } 14 else if(obj.constructor==Object){ 15 var json={}; 16 for(var name in obj){ 17 json[name]=clone(obj[name]); 18 } 19 return json; 20 } 21 else if(obj instanceof HTMLElement){ 22 return obj.cloneNode(true); 23 } 24 else{ 25 return new obj.constructor(obj.valueOf()); 26 } 27 }
测试
1 var arr=[1,2,3]; 2 3 var arr2=clone(arr); 4 5 arr2.pop(); 6 7 console.log(arr2,arr); 8 9 var json={a:1,b:2}; 10 var json2=clone(json); 11 12 json2.b=10101; 13 14 console.log(json2,json); 15 16 var oDate=new Date(); 17 var oDate2=clone(oDate); 18 19 console.log(oDate2,oDate); 20 window.οnlοad=function(){ 21 var oDiv=document.getElementById('div1'); 22 23 //alert(oDiv instanceof HTMLElement); 24 var oDiv2=clone(oDiv); 25 26 alert(oDiv2.id); 27 };