Object.assign use

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.

 

 

replicable cloning target object

function clone(origin) { return Object.assign({}, origin); } 

The above object is copied to the original code is an empty object, get a clone of the original object.

However, this method clones, only clone of the original object values ​​itself, it can not be cloned inherited value. If you want to keep the inheritance chain, the following code can be used.

function clone(origin) { let originProto = Object.getPrototypeOf(origin); return Object.assign(Object.create(originProto), origin); }

Guess you like

Origin www.cnblogs.com/jiuxu/p/11725793.html