Es6 JavaScript Object Method Object.assign ()

Source: Internet
Author: User
Tags object object shallow copy wrapper

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
    1. var target = {a:1};
    2. var source1 = {B:2};
    3. var source2 = {C:3};
    4. Object.assign (target, Source1, SOURCE2);
    5. 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
    1. var target = {a:1, b:1};
    2. var source1 = {b:2, c:2};
    3. var source2 = {C:3};
    4. Object.assign (target, Source1, SOURCE2);
    5. Target //{a:1, B:2, c:3}
If there is only one argument, Object.assign returns the parameter directly.

[JavaScript]View PlainCopy
    1. var obj = {a:1};
    2. 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
    1. 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
    1. Object.assign (undefined) //Error
    2. 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
    1. Let obj = {a:1};
    2. Object.assign (obj, undefined) = = = Obj //True
    3. 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
    1. var v1 = ' abc ';
    2. var v2 = true;
    3. var v3 = 10;
    4. var obj = object.assign ({}, V1, V2, v3);
    5. 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
    1. Object (True) //{[[Primitivevalue]]: true}
    2. Object (Ten) //{[[[Primitivevalue]]: ten}
    3. 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
    1. Object.assign ({b: ' C '},
    2. Object.defineproperty ({}, ' invisible ', {
    3. Enumerable: false,
    4. Value: ' Hello '
    5. })
    6. )
    7. {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
    1. Object.assign ({A: ' B '}, {[Symbol (' C ')]: ' d '})
    2. {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
    1. var obj1 = {A: {b:1}};
    2. var obj2 = Object.assign ({}, obj1);
    3. OBJ1.A.B = 2;
    4. 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
    1. var target = {A: {b: ' C ', D: ' E '}}
    2. var Source = {A: {b: ' Hello '}}
    3. Object.assign (target, source)
    4. {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
    1. Object.assign ([1, 2, 3], [4, 5])
    2. [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
    1. Class Point {
    2. Constructor (x, y) {
    3. Object.assign (This, {x, y});
    4. }
    5. }
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
    1. object.assign (someclass.prototype, {  
    2.     somemethod (ARG1, ARG2)  {  
    3.         
    4.     },  
    5.      Anothermethod ()  {  
    6.        
    7.     }  
    8. });   
    9. //   is equivalent to the following notation   
    10. someclass.prototype.somemethod = function  (arg1, arg2)  {   
    11.   
    12. };  
    13. someclass.prototype.anothermethod = function  ()  {  
    14. ...   
    15. };  
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
    1. function Clone (Origin) {
    2. return Object.assign ({}, Origin);
    3. }
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
    1. function Clone (Origin) {
    2. Let Originproto = Object.getprototypeof (origin);
    3. return Object.assign (Object.create (Originproto), origin);
    4. }
(4) Merging multiple objects

Merges multiple objects into an object.

[JavaScript]View PlainCopy
    1. 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
    1. Const Merge = (... sources) = = Object.assign ({}, ... sources);
(5) Specifying a default value for a property

[JavaScript]View PlainCopy
    1. Const DEFAULTS = {
    2. loglevel:0,
    3. OutputFormat: ' html '
    4. };
    5. function ProcessContent (options) {
    6. Let options = Object.assign ({}, DEFAULTS, options);
    7. }
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 ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.