手写深拷贝

85 阅读1分钟

方法一,用JSON:

const b = JSON.parse(JSON.stringfy(a))

使用 JSON 具有以下缺点:

  1. 不支持 Date、正则、undefined、函数等数据
  2. 不支持引用(即 环状结构)

方法二,用递归

要点:

  1. 递归
  2. 判断类型
  3. 检查环
  4. 不拷贝原型上的属性
const deepClone = (a) => {
  if(!cache){
    cache = new Map() // 缓存不能全局,最好临时创建并传递递归
  }
  if(a instanceof Object) { // 不考虑 iframe
    if(cache.get(a)) { return cache.get(a) }
    let result
    if(a. instanceof Function) {
      if(a.prototype) { // 有 prototype 就是普通函数
        result = function(){ return a.apply(this, arguments) }
      }else{
        result = (...args) => { return a.call(undefined, ...args) }
      }
    }else if(a instanceof Array){
      result = []
    }else if(a instanceof Date){
      result = new Data(a - 0)
    }else if(a instanceof RegExp){
      result = new RegExp(a.source, a.flags)
    }else{
    result = {}
    }
    cache.set(a, result)
    for(let key in a) {
      if(a.hasOwnProperty(key)){
        result[key] = deepClone(a[key], cache)
      }
    }
    return result
  }else{
  return a
  }
}