手写一个深拷贝函数

2020-08-17  本文已影响0人  佐伊zero

对不同类型做不同的处理

// 深拷贝

function getType(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1);
}

function copyArray(ori, copy = []) {
  for (const [index, value] of ori.entries()) {
    copy[index] = deepCopy(value);
  }
  return copy;
}

function copyObject(ori, copy = {}) {
  for (const [key, value] of Object.entries(ori)) {

    copy[key] = deepCopy(value);
  }
  return copy;
}

function copyFunction(ori, copy = () => {}) {
  return eval('fn =' + ori.toString());
}

function deepCopy(ori){
  const type = getType(ori);
  let copy;
  switch(type) {
    case 'RegExp':
      return new RegExp(ori);
    case 'Date':
      return new Date(ori);
    case 'Array':
      return copyArray(ori, copy);
    case 'Function':
      return copyFunction(ori, copy);
    case 'Object':
      return copyObject(ori, copy);
    default:
      return ori;
  }
}
function test() {
  console.log(1);
}
let c = {
  a: [1,2,4],
  b: {
    a:1,
    b: {
      c:1
    }
  },
  e: /\.js/,
  f: function() {
    console.log(1);
  }
}

let res = deepCopy(c);
console.log(res.f === c.f)

上一篇下一篇

猜你喜欢

热点阅读