Home >Web Front-end >JS Tutorial >Comprehensive understanding of Object.assign

Comprehensive understanding of Object.assign

小云云
小云云Original
2018-02-08 14:39:231983browse

The Object.assign() method is used to copy the values ​​of all enumerable properties from one or more source objects to the target object. It returns the target object. This article mainly shares with you a comprehensive analysis of Object.assign.

For ease of understanding, mdn's polyfill for Object.assign is posted here

if (typeof Object.assign != 'function') {
  // Must be writable: true, enumerable: false, configurable: true
  Object.defineProperty(Object, "assign", {
    value: function assign(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 over if 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;
    },
    writable: true,
    configurable: true
  });
}

The Object constructor creates an object wrapper for a given value. If the value is null or undefined, it creates and returns an empty object, otherwise, it returns an object whose Type corresponds to the given value. If the value is already an object, it will return that value.
Give me a chestnut

The above is the detailed content of Comprehensive understanding of Object.assign. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn