写个深拷贝(包括方法的拷贝)

352 阅读1分钟

最近也是提桶跑路了,目前的状态除了面试就是闲着,可是人一闲着就容易焦虑,容易胡思乱想,所以就想着写点东西,可是对于我这样的混子来说,深奥的又不会,就只能搞点以前的基础巩固巩固。然后就写个深拷贝。

深拷贝,无非就是区分数据类型,然后复杂数据进行递归,确保每个层级的数据都能拷贝到,唯一需要注意的就是方法的拷贝。

const getType = value =>
  Object.prototype.toString
    .call(value)
    .slice(8, -1)
    .toLowerCase();

const copy = origin => {
  let result;
  const nativeType = getType(origin);

  if (nativeType === 'set') {
    result = new Set();
    origin.forEach(item => result.add(copy(item)));
  } else if (nativeType === 'map') {
    result = new Map();
    origin.forEach((value, key) => result.set(key, copy(value)));
  } else {
    const type = typeof origin;

    if (type === 'object' && type !== 'null') {
      const Parent = origin.constructor;
      result = new Parent();

      for (const key in origin) {
        result[key] = copy(origin[key]);
      }

      return result;
    } else if (type === 'function') {
      const source = origin.toString();

      // 如果对象方法是采用 ES6 的简写方式声明的
      // 则需要添加 function,这里直接采用错误捕获的方式进行区分,也可以写正则区分
      try {
        result = Function(`return ${source}`)();
      } catch (e) {
        result = Function(`return function ${source}`)();
      }

      return result;
    } else {
      result = origin;
    }
  }

  return result;
};

TMD,感觉没啥好说的,就这样吧

深拷贝 - 例子