`Object.assign()`polyfill中`Object(target)`的目的是什么?

Hur*_*elu 5 javascript javascript-objects polyfills ecmascript-6

forObject.assign()MDN页面中,示例polyfillObject()在迭代属性之前首先包装所有源和目标参数.(即Object(target),Object(source1),Object(source2)...).

该文本还提到在返回目标之前将其他属性直接添加到目标.但是,将目标包装Object()在一个对象中的结果不同于简单地扩充属性.(即Object(target).newProp !== target.newProp).

给出的所有示例都将对象作为参数Object.assign().因此,非对象源或目标参数的用例并不清楚.

A)包装参数的目的是什么Object()?(我的印象Object.keys(x)是相同的Object.keys(Object(x))).

B)Object.assign()与非对象一起使用的可能用例是什么?(例如像:Object.assign(1, 'b', [3], true, function(){}))

Mou*_*ser 2

让我们来分解一下:

测试对象是否存在,如果不存在则创建:

if (!Object.assign) {
Run Code Online (Sandbox Code Playgroud)

使方法通过Object.defineProperty并将其添加到Object

    Object.defineProperty(Object, 'assign', {
    enumerable: false,
    configurable: true,
    writable: true,
Run Code Online (Sandbox Code Playgroud)

这里实际的功能被设置。至少需要提供一个目标和一个源。

    value: function(target, firstSource) {
      'use strict';
Run Code Online (Sandbox Code Playgroud)

如果未定义目标,则会抛出错误。

      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert first argument to object');
      }
Run Code Online (Sandbox Code Playgroud)

将目标转换为对象格式。(例如字符串1234[object String]{0: "1", 1: "2", 2: "3", 3: "4", length: 4}.

      var to = Object(target);
Run Code Online (Sandbox Code Playgroud)

现在使用函数的参数对象循环遍历所有源。从 1 开始,因为 0 是目标。

      for (var i = 1; i < arguments.length; i++) {
        var nextSource = arguments[i]; //store the argument in a variable.
        if (nextSource === undefined || nextSource === null) {
          continue; //if the source is undefined continue. 
        }
Run Code Online (Sandbox Code Playgroud)

然后我们需要源对象中的所有(不仅仅是公开的)可枚举属性,Object.keysObject(source).

        var keysArray = Object.keys(Object(nextSource));
Run Code Online (Sandbox Code Playgroud)

迭代键:

        for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
          var nextKey = keysArray[nextIndex]; //select the key from the index.
Run Code Online (Sandbox Code Playgroud)

getOwnPropertyDescriptor以对象的形式向我们提供有关属性的信息。

          var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
Run Code Online (Sandbox Code Playgroud)

如果该属性不是未定义的并且是可枚举的,则将此属性设置为 的属性to

          if (desc !== undefined && desc.enumerable) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
      return to;
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

最后返回to新添加(克隆)的属性。