JS: Does Object.assign() create deep copy or shallow copy

后端 未结 7 1095
粉色の甜心
粉色の甜心 2020-11-30 03:21

I just came across this concept of

var copy = Object.assign({}, originalObject);

which creates a copy of original object into the \"

7条回答
  •  遥遥无期
    2020-11-30 04:11

    As mentioned above, Object.assign() will do a shallow clone, fail to copy the source object's custom methods, and fail to copy properties with enumerable: false.

    Preserving methods and non-enumerable properties takes more code, but not much more.

    This will do a shallow clone of an array or object, copying the source's methods and all properties:

    function shallowClone(src) {
      let dest = (src instanceof Array) ? [] : {};
    
    // duplicate prototypes of the source
      Object.setPrototypeOf(dest, Object.getPrototypeOf(src));
    
      Object.getOwnPropertyNames(src).forEach(name => {
        const descriptor = Object.getOwnPropertyDescriptor(src, name);
        Object.defineProperty(dest, name, descriptor);
      });
      return dest;
    }
    

    Example:

    class Custom extends Object {
      myCustom() {}
    }
    
    const source = new Custom();
    source.foo = "this is foo";
    Object.defineProperty(source, "nonEnum", {
      value: "do not enumerate",
      enumerable: false
    });
    Object.defineProperty(source, "nonWrite", {
      value: "do not write",
      writable: false
    });
    Object.defineProperty(source, "nonConfig", {
      value: "do not config",
      configurable: false
    });
    
    let clone = shallowClone(source);
    
    console.log("source.nonEnum:",source.nonEnum);
    // source.nonEnum: "do not enumerate"
    console.log("clone.nonEnum:", clone.nonEnum);
    // clone.nonEnum: – "do not enumerate"
    
    console.log("typeof source.myCustom:", typeof source.myCustom);
    // typeof source.myCustom: – "function"
    console.log("typeof clone.myCustom:", typeof clone.myCustom);
    // typeof clone.myCustom: – "function"
    

    jsfiddle

提交回复
热议问题