Es6 JavaScript Object Method Object.assign ()December 01, 2016 16:42:34Hits: 38583
1 Basic usage
The Object.assign method is used for merging objects, copying all enumerable properties of the source object (sources) to the destination object (target).
[JavaScript]View PlainCopy
- var target = {a:1};
- var source1 = {B:2};
- var source2 = {C:3};
- Object.assign (target, Source1, SOURCE2);
- Target //{a:1, B:2, c:3}
The first parameter of the Object.assign method is the target object, and the subsequent arguments are the source object.
Note that if the target object has a property with the same name as the source object, or if more than one source object has the same name, the following property overrides the previous property.
[JavaScript]View PlainCopy
- var target = {a:1, b:1};
- var source1 = {b:2, c:2};
- var source2 = {C:3};
- Object.assign (target, Source1, SOURCE2);
- Target //{a:1, B:2, c:3}
If there is only one argument, Object.assign returns the parameter directly.
[JavaScript]View PlainCopy
- var obj = {a:1};
- Object.assign (obj) = = = Obj //True
If the parameter is not an object, it is first turned into an object and then returned.
[JavaScript]View PlainCopy
- typeof Object.assign (2) //"Object"
Because undefined and null cannot be turned into objects, they can be an error if they are arguments.
[JavaScript]View PlainCopy
- Object.assign (undefined) //Error
- Object.assign (null) //Error
If non-object parameters appear in the location of the source object (that is, non-first parameter), the processing rules are different. First, these parameters are all turned into objects, and if they cannot be turned into objects, they are skipped. This means that if undefined and null are not in the first argument, there will be no error.
[JavaScript]View PlainCopy
- Let obj = {a:1};
- Object.assign (obj, undefined) = = = Obj //True
- Object.assign (obj, null) = = = Obj //True
Other types of values (that is, numeric, string, and Boolean values) are not in the first parameter and do not error. However, except that the string is copied into the target object as an array, the other values do not produce an effect.
[JavaScript]View PlainCopy
- var v1 = ' abc ';
- var v2 = true;
- var v3 = 10;
- var obj = object.assign ({}, V1, V2, v3);
- Console.log (obj); //{"0": "A", "1": "B", "2": "C"}
In the above code, V1, V2, and V3 are strings, booleans, and numeric values, and only strings are combined into the target object (in the form of a character array), and values and Booleans are ignored. This is because only the wrapper object of the string produces an enumerable property.
[JavaScript]View PlainCopy
- Object (True) //{[[Primitivevalue]]: true}
- Object (Ten) //{[[[Primitivevalue]]: ten}
- Object (' abc ') //{0: "A", 1: "B", 2: "C", Length:3, [[Primitivevalue]]: "ABC"}
In the above code, Boolean values, numeric values, and strings are turned into corresponding wrapper objects, and you can see that their original values are in the wrapper object's internal property [[Primitivevalue]], and this property is not copied by Object.assign. Only the wrapper object of the string will produce an enumerable literal attribute, and those attributes will be copied.
The properties of a object.assign copy are limited, copying only the properties of the source object itself (without copying the inheritance property), and not the non-enumerable properties (Enumerable:false).
[JavaScript]View PlainCopy
- Object.assign ({b: ' C '},
- Object.defineproperty ({}, ' invisible ', {
- Enumerable: false,
- Value: ' Hello '
- })
- )
- {b: ' C '}
In the above code, the object object.assign to be copied has only one non-enumerable property invisible, and this property is not copied.
Attributes that are named Symbol values are also object.assign copied.
[JavaScript]View PlainCopy
- Object.assign ({A: ' B '}, {[Symbol (' C ')]: ' d '})
- {A: ' B ', Symbol (c): ' d '}
2 Attention Points
The Object.assign method implements a shallow copy rather than a deep copy. That is, if the value of a property of the source object is an object, then the target object copy gets a reference to the object.
[JavaScript]View PlainCopy
- var obj1 = {A: {b:1}};
- var obj2 = Object.assign ({}, obj1);
- OBJ1.A.B = 2;
- OBJ2.A.B //2
In the above code, the value of the A property of the source object Obj1 is an object, and the object.assign copy gets a reference to the object. Any changes to this object will be reflected on the target object.
For this nested object, once the property with the same name is encountered, the Object.assign method is replaced instead of added.
[JavaScript]View PlainCopy
- var target = {A: {b: ' C ', D: ' E '}}
- var Source = {A: {b: ' Hello '}}
- Object.assign (target, source)
- {A: {b: ' Hello '}}
In the above code, the A property of the target object is replaced by the entire a property of the source object, without the result of {a: {b: ' Hello ', D: ' E '}}. This is usually not what the developer wants, and requires special care.
Some libraries provide a custom version of Object.assign (such as the Lodash _.defaultsdeep method), which solves the problem of shallow copy, resulting in deep copy merging.
Note that object.assign can be used to manipulate arrays, but it treats arrays as objects.
[JavaScript]View PlainCopy
- Object.assign ([1, 2, 3], [4, 5])
- [4, 5, 3]
In the above code, Object.assign treats the array as an object whose property name is 0, 1, 2, so that the No. 0 Number Property 4 of the destination array overrides the No. 0 number attribute 1 of the original array.
3 Common Uses
(1) Adding properties to an object
[JavaScript]View PlainCopy
- Class Point {
- Constructor (x, y) {
- Object.assign (This, {x, y});
- }
- }
The above method adds the X attribute and Y property to the object instance of the point class through the Object.assign method.
(2) Adding a method to an object
[JavaScript]View PlainCopy
- object.assign (someclass.prototype, {
- somemethod (ARG1, ARG2) {
-
- },
- Anothermethod () {
-
-     }  
- });
- // is equivalent to the following notation
- someclass.prototype.somemethod = function (arg1, arg2) {
-
- };
- someclass.prototype.anothermethod = function () {
- ...
- };  
The above code uses a concise representation of the object's properties, placing two functions directly in curly braces, and then adding them to Someclass.prototype using the Assign method.
(3) Cloning objects
[JavaScript]View PlainCopy
- function Clone (Origin) {
- return Object.assign ({}, Origin);
- }
The above code copies the original object to an empty object, and the original object is cloned.
However, cloning in this way can only clone the value of the original object itself, and it cannot clone the value it inherits. If you want to keep the inheritance chain, you can use the following code.
[JavaScript]View PlainCopy
- function Clone (Origin) {
- Let Originproto = Object.getprototypeof (origin);
- return Object.assign (Object.create (Originproto), origin);
- }
(4) Merging multiple objects
Merges multiple objects into an object.
[JavaScript]View PlainCopy
- Const MERGE = (target, ... sources) = Object.assign (target, ... sources);
If you want to return a new object after merging, you can override the above function to merge an empty object.
[JavaScript]View PlainCopy
- Const Merge = (... sources) = = Object.assign ({}, ... sources);
(5) Specifying a default value for a property
[JavaScript]View PlainCopy
- Const DEFAULTS = {
- loglevel:0,
- OutputFormat: ' html '
- };
- function ProcessContent (options) {
- Let options = Object.assign ({}, DEFAULTS, options);
- }
In the above code, the Defaults object is the default value, and the Options object is a user-supplied parameter. The Object.assign method merges defaults and options into a new object, and if both have the same name, the property value of option overrides the Defaults property value.
Note that because of a deep copy problem, the values of all the properties of the defaults object and the options object can only be simple types and cannot point to another object. Otherwise, it will cause the property of the defaults object to have no effect.
Es6 JavaScript Object Method Object.assign ()