Borrow a few words from @rowboat big guy

  • A shallow copy creates a new object with an exact copy of the original object’s property values. If the property is a primitive type, it copies the value of the primitive type, and if the property is a reference type, it copies the memory address, so if one object changes the address, it affects the other object.

  • A deep copy is a complete copy of an object from the heap, creating a new area of the heap to store the new object, and modifying the new object does not affect the original object.

// The code implements deep copy
function deepClone(obj, weakmap = new WeakMap(a)) {
  // limit judgment
  if (obj instanceof RegExp) {
    return new RegExp(obj)
  }
  if (obj instanceof Date) {
    return new Date(obj)
  }
  if (typeofobj ! = ='object') {
    return obj
  }
  if (weakmap.has(obj)) {
    return weakmap.get(obj)
  }
  // Select first
  let target = new obj.__proto__.constructor()
  weakmap.set(obj, target)
  / / superior to let target = Object. The prototype. ToString. Call (obj) = = = '[Object Array]'? [] : {}
  for (let i in obj) {
    if (obj.hasOwnProperty(i)) {
      if (typeof obj[i] === 'object') {
        target[i] = deepClone(obj[i], weakmap)
      } else {
        target[i] = obj[i]
      }
    }
  }
  return target
}
Copy the code