deepClone.js 833 B

12345678910111213141516171819
  1. function deepClone(obj, hash = new WeakMap()) {
  2. if (obj === null) return obj; // 如果是null或者undefined我就不进行拷贝操作
  3. if (obj instanceof Date) return new Date(obj);
  4. if (obj instanceof RegExp) return new RegExp(obj);
  5. // 可能是对象或者普通的值 如果是函数的话是不需要深拷贝
  6. if (typeof obj !== "object") return obj;
  7. // 是对象的话就要进行深拷贝
  8. if (hash.get(obj)) return hash.get(obj);
  9. let cloneObj = new obj.constructor();
  10. // 找到的是所属类原型上的constructor,而原型上的 constructor指向的是当前类本身
  11. hash.set(obj, cloneObj);
  12. for (let key in obj) {
  13. if (obj.hasOwnProperty(key)) {
  14. // 实现一个递归拷贝
  15. cloneObj[key] = deepClone(obj[key], hash);
  16. }
  17. }
  18. return cloneObj;
  19. }