浅拷贝和深拷贝

55 阅读1分钟

浅拷贝

创建一个新对象,这个对象有着原始对象属性值的一份精确拷贝。如果属性是基本类型,拷贝的就是基本类型的值,如果属性是引用类型,拷贝的就是内存地址 ,所以如果其中一个对象改变了这个地址,就会影响到另一个对象。

实现方式

方法一:Object.assign({},objects)

方法二:lodash工具的_.clone(objects)

深拷贝

深拷贝会拷贝所有的属性,并拷贝属性指向的动态分配的内存。当对象和它所引用的对象一起拷贝时即发生深拷贝。深拷贝相比于浅拷贝速度较慢并且花销较大。拷贝前后两个对象互不影响。

实现方式

方法一:JSON.parse(JSON.stringify(objects))

缺点:不支持 Date、正则、undefined、函数等数据,不支持引用(即环状结构)

方法二:lodash工具的 _.cloneDeep(objects)

方法三:手写深拷贝


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) {
      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 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) { 
      if(a.hasOwnProperty(key)){
        result[key] = deepClone(a[key], cache) 
      }
    }
    return result
  } else {
    return a
  }
}

const a = { 
  number:1, bool:false, str: 'hi', empty1: undefined, empty2: null, 
  array: [
    {name: 'dlxx', age: 18},
    {name: 'dlcc', age: 19}
  ],
  date: new Date(2000,0,1,20,30,0),
  regex: /.(j|t)sx/i,
  obj: { name:'dlxx', 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