深度克隆

深度克隆常见的有三种方法:

1.使用对象和数组的toString区别来区分,数组尽管为特殊的对象,但数组尤其自己的toString方法。

 1     function deepclone(Parent, Child) {
 2       for(var prop in Parent) {/*为引用,则判为数组或对象*/
 3           if(Parent.hasOwnProperty(prop)){
 4             if(typeof Parent[prop] == 'object'){
 5                 Child[prop] = (Object.prototype.toString.call(Parent[prop]) == '[object Array]') ? [] : {};
 6                   deepclone(Parent[prop], Child[prop]);
 8                     }
 9             else {/*非引用直接赋值*/
10                         Child[prop] = Parent[prop];
11                     }
12                 }
13             }
14         }            

2.使用instance来判赋值值的原型为数组还是对象来区分; A instanceof Array/Object,来判断A的原型为数组还是对象。

 1 function deepclone(Parent, Child){
 2             for(var prop in Parent){
 3                 if(Parent.hasOwnProperty(prop)){
 4                     if(typeof Parent[prop] == 'object'){
 5                     Child[prop] = Parent[prop] instanceof Array ? [] : {};
 6                     deepclone(Parent[prop], Child[prop]);
 7                     }
 8                     else {
 9                         Child[prop] = Parent[prop];
10                     }
11                 }
12             }
13         }

3.使用构造器constructor来区分数组和对象。

  

 1 function deepclone(Parent, Child){
 2             for(var prop in Parent){
 3                 if(Parent.hasOwnProperty(prop)){
 4                     if(typeof Parent[prop] == 'object'){
 5                     Child[prop] = Parent[prop].constructor === Array ? [] : {};
 6                     deepclone(Parent[prop], Child[prop]);
 7                     }
 8                     else {
 9                         Child[prop] = Parent[prop];
10                     }
11                 }
12             }
13         }

总结:1.分两步:1判断传递的是引用值还是原始值。2.若为原始值则直接赋值传递;若为引用值则区分是数组还是对象,进而创建新的空数组还是空对象,最后递归即可。

   2.重点在数组和对象的判断。

posted @ 2016-02-28 11:53  Walker-lyl  阅读(244)  评论(0)    收藏  举报