当前位置:网站首页>对象深复制,面试题

对象深复制,面试题

2022-08-09 22:05:00 勇敢*牛牛

function cloneDeep(source,target){
    
    if(!target){
    
       switch(true){
    
            case source instanceof Function:
            var arr=source.toString().replace(/\n/g,"").match(/.*\((.*?)\)\s*\{(.*)\}/).slice(1);
            target=new Function(arr[0],arr[1]);
                break;
            case source instanceof HTMLElement:
                target=source.cloneNode(true);
                break;
            case source instanceof Array:
                 target=new source.constructor();
                break
            case source instanceof Date:
            case source instanceof Set:
            case source instanceof Map:
            case Boolean(source.buffer):
                target=new source.constructor(source);
                break
            case source instanceof RegExp:
                target=new RegExp(source.source,source.flags);
                break
            default:
                target={
    };
       }
    }
    // console.log(target)
// var names=[...Object.getOwnPropertyNames(source),...Object.getOwnPropertySymbols(source)];
    var names=Reflect.ownKeys(source);
    for(var i=0;i<names.length;i++){
    
        var key=names[i];
        if(key==="prototype"){
    
            var con=target.prototype.constructor;
            Object.defineProperties(target.prototype,Object.getOwnPropertyDescriptors(source.prototype));
            Object.defineProperty(target.prototype,"constructor",{
    value:con});
            continue;
        }
        var desc=Object.getOwnPropertyDescriptor(source,key);
        if(desc.value instanceof Object){
    
            Object.defineProperty(target,key,{
    
                enumerable:desc.enumerable,
                configurable:desc.configurable,
                writable:desc.writable,
                value:cloneDeep(desc.value)
            })
        }else{
    
            Object.defineProperty(target,key,desc);
        }
    }
    return target;
}

var o1=cloneDeep(obj);
原网站

版权声明
本文为[勇敢*牛牛]所创,转载请带上原文链接,感谢
https://niuniu.blog.csdn.net/article/details/126255354