Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Is assign the es6 method?

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail whether assign is an es6 method. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Assign is the es6 method. Assign () is a new method added to the es6 Object object. The "Object.assign ()" method is used for object merging and copies all enumerable properties of the source object to the target object; the first parameter of this method is the target object, and the subsequent parameters are the source object.

The operating environment of this tutorial: windows7 system, ECMAScript version 6, Dell G3 computer.

Assign is the es6 method.

Object.assign () is a new method added by es6 to merge objects and copy all enumerable properties of the source object (source) to the target object (target).

Const target = {a: 1, b: 2} const source = {b: 4, c: 5} const returnedTarget = Object.assign (target, source) target / / {a: 1, b: 4, c: 5} returnedTarget / / {a: 1, b: 4, c: 5}

The first parameter of the Object.assign method is the target object, and the following parameters are the source object.

Note: if the target object has an attribute with the same name as the source object, or if more than one source object has an attribute with the same name, the following properties override the previous properties.

Const target = {target 1, b: 1} const source1 = {target 2, c: 2} const source2 = {CRAV 3} Object.assign (target, source1, source2) target / / {aVera 1, b: 2, CRAV 3}

If there is only one parameter, Object.assign returns that parameter directly.

Const obj = {a: 1} Object.assign (obj) / / {a: 1} Object.assign (obj) = obj / / true

If the parameter is not an object, it is converted to an object and then returned.

Typeof Object.assign (2) / / "object"

Because undefined and null cannot be converted to objects, an error will be reported if they are used as parameters.

Object.assign (undefined) / / error report Object.assign (null) / / error report

If the non-object parameter appears at the location of the source object (that is, not the first parameter), the processing rules are different. First, these parameters are converted to objects, and if they cannot be converted to objects, they are skipped. This means that if undefined and null are not in the first parameter, no error will be reported.

Let obj = {a: 1} Object.assign (obj, undefined) = obj / / trueObject.assign (obj, null) = obj / / true

Other types of values (that is, numeric, string, and Boolean values) are not in the first parameter and will not report an error. However, none of the values have any effect except that the string is copied into the target object as an array.

Const v1 = 'abc'const v2 = trueconst v3 = 10const obj = Object.assign ({}, v1, v2, v3) obj / / {"0": "a", "1": "b", "2": "c"}

In the above code, v1, v2, and v3 are strings, Boolean values, and numeric values, respectively. As a result, only strings are merged into the target object (in the form of a character array), and numeric and Boolean values are ignored. This is because only a wrapper object with a string produces enumerable properties.

Object.assign (true) / / {[[PrimitiveValue]]: true} Object.assign (10) / {[[PrimitiveValue]]: 10} Object.assign ('abc') / / {0: "a", 1: "b", 2: "c", length: 3, [[PrimitiveValue]]: "abc"}

In the above code, Boolean values, numeric values, and strings are converted to the corresponding wrapper object, respectively. You can see that their original values are all above the internal attribute [[PrimitiveValue]] of the wrapper object, which will not be copied by Object.assign. Only the wrapper object of the string produces enumerable semantic properties, and those properties are copied.

The attributes copied by Object.assign are limited, copying only the properties of the shell source object itself (no inherited attributes), nor non-enumerable properties (enumerable: false).

Object.assign ({b:'c'}, Object.defineProperty ({}, 'invisible', {enumerable: false, value:' hello'})) / / {b:'c'}

In the above code, the only object to be copied by Object.assign is a non-enumerable property, invisible, which is not copied in.

Properties with the name Symbol value are also copied by Object.assign.

Object.assign ({a:'b'}, {[Symbol ('c')]:'d'}) / {a: 'baked, Symbol (c):' d'}

Pay attention

(1) shallow copy

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

Const obj1 = {a: {b: 1}} const obj2 = Object.assign ({}, obj1) obj1.a.b = 2obj2.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 that object. Any changes to this object will be reflected on the target object.

(2) replacement of attributes with the same name

For such nested objects, once an attribute of the same name is encountered, Object.assign handles it by replacing it rather than adding it.

Const target = {a: {b: 'target, d:' e'}} const source = {a: {b: 'hello'}} Object.assign (target, source) / / {a: {b:' hello'}}

In the above code, the a property of the target object is completely replaced by the a property of the source object, instead of the result of {a: {b: 'hello', d:' e'}}. This is usually not what developers want, and you need to be very careful.

Some libraries provide customized versions of Object.assign (such as the _ .defaultsDeep method of Lodash) to merge deep copies.

(3) the array processing Object.assign can be used to deal with the array, but the array is treated as an object.

Object.assign ([1,2,3], [4,5]) / / [4,5,3]

In the above code, Object.assign treats the array as an object with property names 0, 1, and 2, so attribute 4 of the source array overrides attribute 1 of the target array.

(4) the treatment of value function

Object.assign can only copy values. If the value to be copied is a value function, it will be evaluated and then copied.

Const source = {get foo () {return 1}} const target = {} Object.assign (target, source) / / {foo: 1}

In the above code, the foo property of the source object is a value function. Object.assign will not copy this value function, but will only copy the value after it has been obtained.

The usage of Object.assign

The Object.assign method has many uses.

(1) add attributes to the object

Class Point {constructor (x, y) {Object.assign (this, {x, y})}}

The above method adds the x and y attributes to the object instance of the Point class through the Object.assign method.

(2) add a method to the object

Object.assign (SomeClass.prototype, {someMethod (arg1, arg2) {}, anotherMethod () {}}) / / is equivalent to the following writing: SomeClass.prototype.someMethod = function (arg1, arg2) {} SomeClass.prototype.anotherMethod = function () {}

The above code uses a concise representation of the object's properties, placing the two functions directly in curly braces, and then adding them to the SomeClass.prototype using the assign method.

(3) Clone object

Function clone (origin) {return Object.assign ({}, origin)}

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

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

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

(4) merge multiple objects

Merge multiple objects into an object.

Const merge = (target,... sources) = > Object.assign (target,... sources)

If you want to return a new object after the merge, you can overwrite the above function to merge an empty object.

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

(5) specify the default value for the attribute

Const DEFAULTS = {logLevel: 0, outputFormat: 'html'} function processContent (options) {options = Object.assign ({}, DEFAULTS, options) console.log (options) / /.}

In the above code, the DEFAULTS object is the default value, and the options object is the user-supplied parameter. The Object.assign method merges DEFAULTS and options into a new object, and if both have properties of the same name, the property value of option overrides the property value of DEFAULTS.

Note: due to the problem of shallow copy, the values of all properties of the DEFAULTS object and the options object are preferably simple types and do not point to another object. Otherwise, this property of the DEFAULTS object will most likely not work.

Const DEFAULTS = {url: {host: 'example.com', port: 7070},} processContent ({url: {port: 8000}}) / / {/ / url: {port: 8000} / /}

The original intention of the above code is to change url.port to 8000 dint url.host. The actual result is that options.url overrides DEFAULTS.url, so url.host no longer exists.

This is the end of this article on whether assign is an es6 method. I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report