码迷,mamicode.com
首页 > 其他好文 > 详细

对象的深度克隆

时间:2015-07-12 14:08:58      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:

 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"

 

对象的深度克隆

标签:

原文地址:http://www.cnblogs.com/webliu/p/4640835.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!