当前位置:网站首页>Object. Simple implementation of assign()

Object. Simple implementation of assign()

2022-07-07 12:29:00 Xiaoding Chong duck!

One 、Object.assign()  Introduce

1. Definition :

Object.assign()  Method is used to assign the values of all enumerable properties from one or more source objects to the target objects . It will return the target object .        ——MDN

2. grammar

Object.assign(target, ...sources)

target: Target audience

sources: Source object , You can have as many as you like

Return value : It must be an object

Two 、 Principle and Implementation

1. Analysis characteristics :

(1) The first parameter cannot be null or undefined( I'm not sure why )

(2) The return value must be an object , So no matter what type the first parameter passed in ( except null or undefined), Use both Object() Into objects

(3) Because you can pass multiple object parameters , Then traverse and assign a value to the target object .

2. Code :

function myAssign(target, ...sources) {
    //  The first parameter cannot be null or undefined
    if (target === undefined || target === null) {
      throw new TypeError('cannot convert first argument to object');
    }
    //  What is returned must be an object 
    let res = Object(target);
    for (let i = 0; i < sources.length; i++) {
      let obj = sources[i];
      if (obj !== null && obj !== undefined) {
        for (let k in obj) {
          if (Object.prototype.hasOwnProperty.call(sources[i], k)) {
            res[k] = obj[k];
          }
        }
      }
    }
    return res;
}

summary :

I will know why the attribute of the first layer is deep copy after I write it once , The objects in the object are all shallow copies .

In fact, it just takes out the attributes in the object and assigns them to the target object , But the object of the object is not traversed and assigned .

原网站

版权声明
本文为[Xiaoding Chong duck!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130617454544.html