Basic usage

The Object.assign method is used to merge objects. It copies all the enumerable attributes of the source Object to the target Object.

Usage: Object.assign(target, source)

    const target = { a: 1 };
    const source1 = { b: 2 };
    const source2 = { c: 3 };

    Object.assign(target, source1, source2);
    target // {a:1, b:2, c:3}
Copy the code
  • If the target object has an attribute with the same name as the source object, or if multiple source objects have an attribute with the same name, the following attribute willcoverPrevious properties.
    const target = { a: 1.b: 1 };
    const source1 = { b: 2.c: 2 };
    const source2 = { c: 3 };

    Object.assign(target, source1, source2);
    target // {a:1, b:2, c:3}
Copy the code
  • If I have only one parameter,Object.assignThis parameter is returned directly.
    const obj = {a: 1};
    Object.assign(obj) === obj // true
Copy the code

Object.assign()– shallow copy (copy one layer only)

    let obj = { name: 'lisa'.age: 18.dept: { deptname: 'blackpink'}}let copyObj = Object.assign({}, obj) 

    copyObj.name = 'luo'
    copyObj.dept.deptname = 'pinkblack'

    console.log(obj)    //{ name: 'lisa', age: 18, dept: { deptname: 'pinkblack' } }
    console.log(copyObj) // { name: 'luo', age: 18, dept: { deptname: 'pinkblack' } }
    // For the first layer (base type), the values are copied, and for the reference type, the references are copied.

Copy the code

There are some details is not commonly used May refer to: www.jianshu.com/p/d5f572dd3…