JavaScript 系列 - 拷贝

77 阅读1分钟

浅拷贝

同一引用类型地址

  • 数组
    • slice
    • concat
  • 对象
    • Object.assign
    • 展开运算
function copy(obj) {
  return Object.create(
    Object.getPrototypeOf(obj),
    Object.getOwnPropertyDescriptors(obj)
  );
}

深拷贝

新建引用类型地址

JSON.parse(JSON.stringfy()) 特殊值不适用

const copy = function (from, to) {
  if (typeof from !== "object" && from !== null) {
    return;
  }
  var to =
    to || (Object.prototype.toString.call(from) === "[object Array]" ? [] : {});
  for (var key in from) {
    if (from.hasOwnProperty(key)) {
      if (typeof from[key] === "object") {
        to[key] = copy(from[key]);
      } else {
        to[key] = from[key];
      }
    }
  }
  return to;
};
const extend = function (to, from) {
  for (var property in from) {
    var descriptor = Object.getOwnPropertyDescriptor(from, property);
    if (typeof descriptor.value === "object") {
      to[property] =
        Object.prototype.toString.call(descriptor.value) === "[object Array]"
          ? []
          : {};
      extend(to[property], descriptor.value);
    } else {
      if (
        descriptor &&
        (!descriptor.writable ||
          !descriptor.configurable ||
          !descriptor.enumerable ||
          descriptor.get ||
          descriptor.set)
      ) {
        Object.defineProperty(to, property, descriptor);
      } else {
        to[property] = from[property];
      }
    }
  }
};