对象的深度克隆
1 function clone(obj) { 2 var buf; 3 if(obj instanceof Array){ //被克隆的对象是数组 4 buf = []; 5 var i = obj.length; 6 while(i--){ 7 buf[i] = clone(obj[i]); 8 } 9 return buf; 10 }else if(obj instanceof Object){ //被克隆的对象是对象 11 buf = {}; 12 for (var k in obj){ 13 buf[k] = clone(obj[k]); 14 } 15 return buf; 16 }else{ 17 return obj; //被克隆的是普通类型 18 } 19 } 20 21 22 function F (){ 23 this.name = "liu", 24 this.color = ["red","green"], 25 this.friends = { 26 first : "yangyi", 27 second : "koukou" 28 } 29 } 30 var f = new F(); 31 var fClone = clone(f); 32 console.log(fClone.friends); //{first: "yangyi", second: "koukou"} 33 console.log(fClone.colors); //["red","green"] 34 console.log(fClone.name); //"liu"