Object.assign can merge objects. The syntax looks like this: Object.assign(target,… sources)

Object.assign copies enumerable properties from source to target. Overrides if it has the same name as an existing target attribute. At the same time, subsequent sources overwrite the same attribute of the previous source.

⚠️ object. assign copies the attribute value. If the attribute value is a reference type, then the copy is actually the reference address, which will cause the problem of reference sharing.

For example:

const o1 = { name: 'fedaily' }
const o2 = { topic: ['react'.'nodejs'] }
const o3 = Object.assign({}, o1, o2)

// o3 { name: 'fedaily', topic: ['react'.'nodejs'] }
o3.topic.push('css')

// o3 { name: 'fedaily', topic: ['react'.'nodejs'.'css'] }
// o2 { topic: ['react'.'nodejs'.'css']} // ⚠️ we can see that the topic values of all objects have been updatedCopy the code

So, when we’re happy to use object. assign, we need to pay special attention to whether there are any reference types.

What if we need to deal with reference types, which involve copying objects, see lodash’s _clone, _cloneDeep, etc.

Add the MDN Object. Assign polyfill, convenient for you to understand the internal implementation, and better master this method

if(typeof Object.assign ! ='function') {
  Object.assign = function (target, varArgs) { // .length of function is 2
    'use strict';
    if (target == null) { // TypeError if undefined or null
      throw new TypeError('Cannot convert undefined or null to object');
    }

    var to = Object(target);

    for (var index = 1; index < arguments.length; index++) {
      var nextSource = arguments[index];

      if(nextSource ! = null) { // Skip overif undefined or null
        for (var nextKey in nextSource) {
          // Avoid bugs when hasOwnProperty is shadowed
          if(Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { to[nextKey] = nextSource[nextKey]; }}}}return to;
  };
}
Copy the code