1
function deepClone(obj, hash = new WeakMap()) {
  if (obj === null) return obj; // 如果是null或者undefined我就不进行拷贝操作
  if (obj instanceof Date) return new Date(obj);
  if (obj instanceof RegExp) return new RegExp(obj);
  // 可能是对象或者普通的值  如果是函数的话是不需要深拷贝
  if (typeof obj !== "object") return obj;
  // 循环引用属性的处理
  if (hash.get(obj)) return hash.get(obj);
  // 是对象的话就要进行深拷贝
  let cloneObj = new obj.constructor();
  // 找到的是所属类原型上的constructor,而原型上的 constructor指向的是当前类本身
  hash.set(obj, cloneObj);
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      // 实现一个递归拷贝
      cloneObj[key] = deepClone(obj[key], hash);
    }
  }
  return cloneObj;
}

如果没有 if (hash.get(obj)) return hash.get(obj);这段代码会无限递归下去。
WeakMap是为了不干扰垃圾回收机制:hash.set(obj, cloneObj);对obj产生的引用是弱引用。


fuGUI
1.6k 声望1.9k 粉丝

The best time to plant a tree is ten years ago, and the second,let us start