手写深拷贝

57 阅读1分钟

什么是深拷贝

深拷贝就是源对象与拷贝对象互相独立,其中任何一个对象的改动都不会对另外一个对象造成影响。

JSON方法

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

缺点

  1. 不支持Date、正则、undefined、函数等数据
  2. 不支持引用

递归方法

判断类型,使用递归完成拷贝

const deepClone = (a) => {
if(a instanceof Object){ // 不考虑 iframe
    let result
    if(a instanceof Function){
        // 判断是箭头函数还是普通函数,有prototype就是普通函数
        if(a.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 Date(a - 0)
    } else if(a instanceof RegExp){
        result = new RegExp(a.source, a.flags)
    } else {
        result = {}
    }
    for(let key in a){
        result[key] = deepClone(a[key], cache)
    }
    return result
} else {
    return a
  }
}

检查环

例如a.self = a就会产生环。我们使用缓存来解决。

const deepClone = (a, cache) => {
    if(!cache){
        cache = new Map() // 缓存不能全局,最好临时创建并递归传递
    }
    if(a instanceof Object){ // 不考虑 iframe
        if(cache.get(a)){return cache.get(a)}
        let result
        if(a instanceof Function){
            // 判断是箭头函数还是普通函数,有prototype就是普通函数
            if(a.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 Date(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){
            result[key] = deepClone(a[key], cache)
        }
        return result
    } else {
        return a
    }
}

不拷贝原型上的属性

for(let key in a) { 
    if(a.hasOwnProperty(key)){
        result[key] = deepClone(a[key], cache) 
    }
}

测试代码

const a = { 
  number:1, bool:false, str: 'hi', empty1: undefined, empty2: null, 
  array: [
    {name: 'frank', age: 18},
    {name: 'jacky', age: 19}
  ],
  date: new Date(2000,0,1,20,30,0),
  regex: /.(j|t)sx/i,
  obj: { name:'frank', age: 18},
  f1: (a, b) => a + b,
  f2: function(a, b) { return a + b }
}
a.self = a

const b = deepClone(a)

b.self === b // true
b.self = 'hi'
a.self !== 'hi' //true