Detailed explanation of the usage example code of Object. assign of in ES6

  • 2021-10-16 01:09:31
  • OfStack

Directory 2. Purpose 2.1 Add Attributes to Objects 2.2 Add Methods to Objects 2.3 Clone Objects 2.4 Merge Multiple Objects 2.5 Specify Default Values for Attributes

Method: Object. assign ()
Function: Assign the value of the sourse object to the target object. Both of them will be overwritten. Unique target will be retained. Unique sourse will be added
Usage:

The Object. assign method implements shallow copy, not deep copy. That is, if the value of a property of the source object is an object, the target object copy gets a reference to that object.


var object1 = { a: { b: 1 } };

ar object2 = Object.assign({}, object1);

object1.a.b = 2;

console.log(object2.a.b);

2. Purpose

2.1 Adding Attributes to Objects

2.2 Adding Methods to Objects

2.3 Cloning Objects


function copyFnc(origin) {

return Object.assign({}, origin)}

var sur = { a: 1, b: 2 };

console.log(copyFnc(sur));

The above code copies the original object to an empty object, and gets a clone of the original object.

However, cloning in this way can only clone the value of the original object itself, not the value it inherits. If you want to keep the inheritance chain, you can use the following code.


function clone(origin) {

let originProto = Object.getPrototypeOf(origin);

return Object.assign(Object.create(originProto), origin);

}

In JS, the subclass uses Object. getPrototypeOf to call the parent method to obtain the prototype of the object.

2.4 Merging Multiple Objects

//Multiple objects merge into an object


const merge = (target, ...sources) => Object.assign(target, ...sources);

//Multiple objects merged into a new object


const merge = (...sources) => Object.assign({}, ...sources);

2.5 Specify default values for properties


const DEFAULTS = {
logLevel: 0,
outputFormat: 'html'};
function processContent(options) {let options = Object.assign({}, DEFAULTS, options);
}

Related articles: