Implementation approach
-
Determine if the native Object supports this function. If it doesn’t, create a function assign and bind it to Object using Object.defineProperty.
-
Check whether the parameters are correct (the target object cannot be empty, we can pass in {} directly, but must set the value).
-
Use Object() to convert it to an Object, save it as to, and return the Object to.
-
Use for.. The in loop iterates through all enumerable own properties. And copy it to the new target object (use hasOwnProperty to get its own properties, that is, properties that are not on the prototype chain). The implementation code is as follows. Instead of assign, assign2 is used for easy verification. Note that this mock implementation does not support the Symbol attribute, as there is no symbol in ES5.
if (typeof Object.assign2 ! ='function') {
// Attention 1
Object.defineProperty(Object."assign2", {
value: function (target) {
'use strict';
if (target == null) { // Attention 2
throw new TypeError('Cannot convert undefined or null to object');
}
// Attention 3
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if(nextSource ! =null) { // Attention 2
// Attention 4
for (var nextKey in nextSource) {
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { to[nextKey] = nextSource[nextKey]; }}}}return to;
},
// The default is false, which is enumerable: false. in.. Unable to get property name
writable: true.configurable: true
});
}
Copy the code