分别给出浅克隆和深克隆实现

浅克隆:

        var obj1=obj;
        var obj1=Object.assgin({},obj);
        for(var prop in obj){obj1[prop]=obj[prop]}
        var obj1={...obj};

深克隆:

    var obj1=JSON.parse(JSON.stringify(obj));==========无法复制函数和undefined

牛逼的来了=========================除了DOM和二进制流

         function cloneObj(source,target){
                 if(!target){
                     if(source.constructor===RegExp){
                         target=new RegExp(source.source,source.flags);
                     }else{
                         target=new source.constructor();
                     }
                 }
                 var names=Object.getOwnPropertyNames(source);
                 for(var i=0;i<names.length;i++){
                     var desc=Object.getOwnPropertyDescriptor(source,names[i]);
                     if(typeof desc.value==="object" && desc.value!==null){
                         var values=cloneObj(desc.value);
                         Object.defineProperty(target,names[i],{
                             enumerable:desc.enumerable,
                             configurable:desc.configurable,
                             writable:desc.writable,
                             value:values
                         });
                     }else{
                         Object.defineProperty(target,names[i],desc);
                     }
                 }
                 return target;
             }

 

posted @ 2019-08-17 00:15  吴小明-  阅读(227)  评论(0编辑  收藏  举报