gpt4 book ai didi

javascript - `Object(target)` polyfill 中 `Object.assign()` 的用途是什么

转载 作者:搜寻专家 更新时间:2023-11-01 04:31:17 25 4
gpt4 key购买 nike

MDN page forObject.assign()在遍历属性之前,示例 polyfill 首先将所有源和目标参数包装在 Object() 中。(即 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(){}) )

最佳答案

让我们分解一下:

Test if the object exists, if not make it:

if (!Object.assign) {

Make the method via Object.defineProperty and add it to Object

    Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,

Here the actual function gets set. One needs to supply a target and one source minimum.

    value: function(target, firstSource) {
'use strict';

If the target is not defined throw an error.

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

Cast the target to Object format. (E.g. String 1234 to [object String]{0: "1", 1: "2", 2: "3", 3: "4", length: 4}.

      var to = Object(target);

Now loop through all sources using the arguments object of the function. Start with 1, since 0 is the target.

      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.
}

Then we need all (not only the exposed) the enumerable properties from the source object, use Object.keys in combination with Object(source).

        var keysArray = Object.keys(Object(nextSource));

Iterate over the keys:

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

getOwnPropertyDescriptor gives us information about the property in the form of an object.

          var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);

If the property is not undefined and is enumerable then set this property as a property to to.

          if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
});
}

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

关于javascript - `Object(target)` polyfill 中 `Object.assign()` 的用途是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28657071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com