JS 深浅拷贝

JS 深浅拷贝

浅拷贝

ES6 Object assign

var A1 = { a: "2" };
var A2 = Object.assign({}, A1);

Object assign 的兼容写法

if (!Object.assign) {
  Object.defineProperty(Object, 'assign', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function(target) {
      'use strict';
      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert first argument to object');
      }

      var to = Object(target);
      for (var i = 1; i < arguments.length; i++) {
        var nextSource = arguments[i];
        if (nextSource === undefined || nextSource === null) {
          continue;
        }
        nextSource = Object(nextSource);

        var keysArray = Object.keys(nextSource);
        for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
          var nextKey = keysArray[nextIndex];
          var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
          if (desc !== undefined && desc.enumerable) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
      return to;
    }
  });
}

ES6 Spread Syntax

var A1 = { a: "2" };
var A3 = { ...A1 };  // Spread Syntax

深拷贝

stringfy

假设你的对象只包含变量,没有 functions:

var newObject = JSON.parse(JSON.stringify(oldObject));

使用 library