ES6's Object.assign () usage detailed explanation

Object.assign()

introduce

This method is a new interface of ES6, which can receive multiple parameters: the first parameter is the target object, and the latter parameter is the source object; its function is to merge multiple js objects: merge multiple source objects into the target object On the above, if an attribute (method) with the same name appears and then merged, it will overwrite the previously merged attribute (method) with the same name. That is, the latter has a higher priority. assign will not merge non-enumerable properties

demo

let target = {
    
     a: 1 };
let source1 = {
    
     b: 2 };
let source2 = {
    
     c: 3 };
let source3 = {
    
     b: 4 };
console.log(Object.assign(target, source1, source2, source3));
// { a: 1, b: 4, c: 3 }

question

Problem 1: Parameter type problem

The main purpose of Object.assign() design is to merge objects, so theoretically the parameter it receives is an object type; if the parameter is not an object type, it is first converted to an object type and then merged.

Notice

  • If target is not an object, it will be converted to an object; if it cannot be converted, an error will be reported
  • if source is not an object, it is converted to an object; if it cannot be converted, it is ignored
  • null, undefined cannot be converted to object type
let target = {
    
    };
let source1 = 'abc';
let source2 = null;
let source3 = {
    
     "2": 4 };
console.log(Object.assign(target, source1, source2, source3));
// { '0': 'a', '1': 'b', '2': 4 }

Problem 2: Copy Attribute Restrictions

The properties copied by Object.assign are limited. Only the properties of the object itself (not inherited properties) will be copied, and non-enumerable properties will not be copied. But the attribute named Symbol value can be copied by Object.assign.

Question 3: Is the copy a deep copy? Shallow copy?

The copy made by Object.assign is a shallow copy. That is to say, if the value of the copied attribute is a compound attribute such as an object, only one reference can be copied.

const obj1 = {
    
    a: {
    
    b: 1}};
const obj2 = Object.assign({
    
    }, obj1);
 
obj1.a.b = 2;
obj2.a.b // 2

Application Scenario

1. Add attributes to the object

class Point{
   constructor(x,y){
      Object.assign(this,{x,y});
   }
}

The above method can add attribute x and attribute y to the instance object of object Point class.

2. Add methods to objects

// 方法也是对象
// 将两个方法添加到类的原型对象上
// 类的实例会有这两个方法
Object.assign(SomeClass.prototype,{
    someMethod(arg1,arg2){...},
    anotherMethod(){...}
});

After adding methods to the prototype object of the class, instances of the class can inherit these two methods.

3. Clone objects

//克隆对象的方法
function clone(origin){
    //获取origin的原型对象
    let originProto = Obejct.getPrototypeOf(origin);
    //根据原型对象,创建新的空对象,再assign
    return Object.assign(Object.create(originProto),origin);
}

4. Specify default values ​​for attributes

// 默认值对象
const DEFAULTS = {
   logLevel : 0,
   outputFormat : 'html'
};
 
// 利用assign同名属性会覆盖的特性,指定默认值,如果options里有新值的话,会覆盖掉默认值
function processContent(options){
   options = Object.assign({},DEFAULTS,options);
   console.log(options);
   //...
}

For the sake of shallow copy of assign, the values ​​of the DEFAULTS object and the options object should preferably be simple type values ​​at this time, otherwise the function will fail.

const DEFAULTS = {
  url: {
    host: 'example.com',
    port: 7070
  },
};
 
processContent({ url: {port: 8000} })
// {
//   url: {port: 8000}
// }

In the above code, since url is an object type, the default url is overwritten, but the host attribute is missing inside, forming a bug.

Replenish

transfer object

Object(true)  // {[[PrimitiveValue]]: true}
Object(10)    // {[[PrimitiveValue]]: 10}
Object('abc') // {0: "a", 1: "b", 2: "c", length: 3, [[PrimitiveValue]]: "abc"}

Guess you like

Origin blog.csdn.net/weixin_45268025/article/details/123925407