object.js 892 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. function clone(target, source, isDeep = true) {
  2. // 浅拷贝使用内置方法
  3. if (!isDeep) {
  4. return Object.assign(target, source);
  5. }
  6. // 递归遍历拷贝成员
  7. for (let item in source) {
  8. if (source[item] instanceof Object) {
  9. // 检测对象还是数组
  10. target[item] =
  11. Object.prototype.toString.call(source[item]) === '[object Array]' ? [] : {};
  12. clone(target[item], source[item], isDeep);
  13. } else {
  14. target[item] = source[item];
  15. }
  16. }
  17. return target;
  18. }
  19. function cloneWithSelf(target, source, isDeep = true) {
  20. // 先拷贝target自身
  21. const o = Object.clone({}, target, isDeep);
  22. return Object.clone(o, source, isDeep)
  23. }
  24. // 给原型对象扩展方法
  25. Object.assign(Object, {
  26. clone,
  27. cloneWithSelf
  28. })
  29. export default {
  30. clone,
  31. cloneWithSelf
  32. }