Method : Object.assign() The Object.assign method performs a shallow copy, not a deep copy. That is to say, if the value of a property of the source object is an object, then the target object copies a reference to this object. var object1 = { a: { b: 1 } }; ar object2 = Object.assign({}, object1); object1.ab = 2; console.log(object2.ab); 2. Purpose2.1 Adding properties to objects2.2 Adding methods to objects2.3 Cloning Objectsfunction 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 we get a clone of the original object. However, using this method to clone can only clone the values of the original object itself, not the values 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 class method to obtain the prototype of the object. 2.4 Merging multiple objects//Merge multiple objects into one object const merge = (target, ...sources) => Object.assign(target, ...sources); //Merge multiple objects into a new object const merge = (...sources) => Object.assign({}, ...sources); 2.5 Specifying default values for propertiesconst DEFAULTS = { logLevel: 0, outputFormat: 'html'}; function processContent(options) {let options = Object.assign({}, DEFAULTS, options); } This is the end of this article about the usage and purpose of ES6 Object.assign(). For more information about the usage of ES6 Object.assign(), please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Example code for implementing anti-shake in Vue
>>: JS removeAttribute() method to delete an attribute of an element
This article example shares the specific code of ...
The content attribute is generally used in the ::...
1. To prohibit all IP addresses from accessing th...
Comments and messages were originally a great way...
Locks in MySQL Locks are a means to resolve resou...
I have been learning about algorithms recently an...
JavaScript now releases a new version every year,...
In the previous article, we introduced the MySQL ...
Table of contents 1. Static implementation method...
Table of contents 1. Structure string 2. Return t...
1. It is preferred to use the root user to log in...
Netfilter Netfilter is a packet processing module...
It is very common to see images and text displaye...
MySQL 5.7.18 installation and problem summary. I ...
Preface The optional chaining operator (?.) allow...