手写深拷贝

106 阅读1分钟
function deepClone(obj,cache = new Map()){
    if(cache.get(obj)){
        return cache.get(obj)
    }
    if(obj instanceof Object){
        let dist ;
        if(obj instanceof Array){
          // 拷贝数组
          dist = [];
        }else if(obj instanceof Function){
          // 拷贝函数
          dist = function () {
            return obj.call(this, ...arguments);
          };
        }else if(obj instanceof RegExp){
          // 拷贝正则表达式
         dist = new RegExp(obj.source,obj.flags);
        }else if(obj instanceof Date){
            // 拷贝时间对象
            dist = new Date(obj);
        }else{
          // 拷贝普通对象
          dist = {};
        }
        // 将属性和拷贝后的值作为一个map
        cache.set(obj, dist);
        for(let key in obj){
            // 过滤掉原型身上的属性
          if (obj.hasOwnProperty(key)) {
              dist[key] = deepClone(obj[key], cache);
          }
        }
        return dist;
    }else{
        return obj;
    }
}