The combined Object.assign () object - ES6

 

Object.assignA method for merging the object, the source object (source) of all enumerated attribute, copied to the target object (target).

const target = { a: 1 };

const source1 = { b: 2 };
const source2 = { c: 3 };

Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}

 

Object.assignThe first parameter is the target object's method, the source object parameters are behind.

Note that if the source object and the target object has attributes with the same name, or a plurality of source objects of the same name attribute, after the attribute overwrite the previous attribute.

const target = { a: 1, b: 1 };

const source1 = { b: 2, c: 2 };
const source2 = { c: 3 };

Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}

 

important point

(1) shallow copy

Object.assignThe method is practiced shallow copy, rather than a deep copy. That is, the value of a property if the source object is an object, then get a copy of the target object is a reference to the object.

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

obj1.a.b = 2;
obj2.a.b // 2

 

In the above code, the source object obj1of the avalue of the attribute is an object, Object.assignthe copy obtained is a reference to the object. Any change in this object, will be reflected in the destination object.

(2) replacement of the same name attribute

For this nested object, the event attribute of the same name, Object.assignthe processing method is to replace, rather than adding.

const target = { a: { b: 'c', d: 'e' } }
const source = { a: { b: 'hello' } }
Object.assign(target, source)
// { a: { b: 'hello' } }

The above code, targetobject aattributes are sourceobject aproperties of the entire replaced, while not get { a: { b: 'hello', d: 'e' } }results. This is usually not the developers want, need special care.

Some libraries offer Object.assigncustomized versions (such as Lodash of the _.defaultsDeepmethod) can be obtained with deep copies.

(3) processing array

Object.assignIt can be used to handle an array, but the array will treated as objects.

Object.assign([1, 2, 3], [4, 5])
// [4, 5, 3]

 

In the above code, Object.assignthe array as an object property named 0,1,2, the source array property 0 4covered 0 properties of the target array 1.

Process (4) the value of the function

Object.assignCopy only values, if you want to copy the value is a function of the value, then evaluated and then copied.

const source = {
  get foo() { return 1 }
};
const target = {};

Object.assign(target, source)
// { foo: 1 }

The above code, sourceobject fooattribute value is a function that Object.assigndoes not copy the values of the function, only later to get the value, copy this value in the past.



 

Guess you like

Origin www.cnblogs.com/LChenglong/p/12175115.html