手写一个深拷贝

  1. 递归
  2. 判断类型
  3. 检测循环引用(环)
  4. 不可能拷贝 proto

    const cache = new Map()//缓存已拷贝部分
    function clone(object){
      if(cache.get(object)){//假如已缓存,直接返回
          return cache.get(object)
      }
      let result
      if(! (object instanceof Object) ){//基础类型直接返回
          return object
      }else if(object instanceof Array){
          result = []
      }else if(object instanceof Function){
         result = function(){return object.apply(this,arguments)}
      }else if(object instanceof Date){
          result = new Date(object-0)
      }
      else if(object instanceof RegExp){
          result = new RegExp(a)
      }else{
          result = {}
      }
      cache.set(object,result)//插入缓存
      for(let key in object){
          if(object.hasOwnProperty(key)){//非继承属性
              result[key] = clone(object[key])
          }
      }
      return result
    }