Is assign an es6 method?
assign is an es6 method. assign() is a new method of the es6 Object object. The "Object.assign()" method is used to merge objects. It can copy all enumerable properties of the source object to the target object; the first one of this method The parameter is the target object, and the subsequent parameters are all source objects.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
assign is an es6 method.
Object.assign() is a new method in es6, used for merging objects, copying all enumerable properties of the source object (source) to the target on the 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 }
Object.assign
The first parameter of the method is the target object, and the subsequent parameters are all source objects.
Note: If the target object and the source object have attributes with the same name, or multiple source objects have attributes with the same name, the later attributes will overwrite the previous attributes.
const target = { a: 1, b: 1 } const source1 = { b: 2, c: 2 } const source2 = { c: 3 } Object.assign(target, source1, source2) target // {a:1, b:2, c:3}
If there is only one parameter, Object.assign
will return the parameter directly.
const obj = {a: 1} Object.assign(obj) // {a: 1} Object.assign(obj) === obj // true
If the parameter is not an object, it will be converted into an object first and then returned.
typeof Object.assign(2) // "object"
Since undefined and null cannot be converted into objects, if they are used as parameters, an error will be reported.
Object.assign(undefined) // 报错 Object.assign(null) // 报错
If the non-object parameter appears in the position of the source object (that is, not the first parameter), then the processing rules are different. First, these parameters will be converted into objects. If they cannot be converted into objects, they will be 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 // true Object.assign(obj, null) === obj // true
Other types of values (i.e. numeric values, strings and Boolean values) are not in the first parameter and no error will be reported. However, except that the string will be copied into the target object in the form of an array, other values will have no effect.
const v1 = 'abc' const v2 = true const v3 = 10 const 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 combined into the target object (in the form of a character array), and numeric values and Boolean values will be ignored. This is because only string wrapper objects produce 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, numerical values, and strings are converted into corresponding packaging objects respectively. You can see that their original values are in the internal properties of the packaging object[[PrimitiveValue]]
Above, this attribute will not be copied by Object.assign
. Only string wrapper objects will produce enumerable literal properties, and those properties will be copied.
Object.assign
The copied attributes are limited. Only the source object’s own attributes are copied (inherited attributes are not copied), and non-enumerable attributes are not copied (enumerable: false
).
Object.assign({b: 'c'}, Object.defineProperty({}, 'invisible', { enumerable: false, value: 'hello' }) ) // { b: 'c' }
In the above code, Object.assign
The object to be copied has only one non-enumerable property invisible
, and this property has not been copied.
The attribute named Symbol
value will also be copied by Object.assign
.
Object.assign({ a: 'b' }, { [Symbol('c')]: 'd' }) // { a: 'b', Symbol(c): 'd' }
Notes
(1) Shallow copy
Object.assign
The method implements shallow copy, not deep copy. That is to say, if the value of a certain attribute of the source object is an object, then the copy of the target object will get a reference to this object.
const obj1 = {a: {b: 1}} const obj2 = Object.assign({}, obj1) obj1.a.b = 2 obj2.a.b // 2
In the above code, the value of the a
attribute of the source object obj1
is an object, and Object.assign
is copied to this object. Quote. Any changes to this object will be reflected on the target object.
(2) Replacement of attributes with the same name
For this kind of nested object, once an attribute with the same name is encountered, Object.assign
processing The method is to replace, not to add.
const target = { a: { b: 'c', d: 'e' } } const source = { a: { b: 'hello' } } Object.assign(target, source) // { a: { b: 'hello' } }
In the above code, the a
attribute of the target
object is completely replaced by the a
attribute of the source
object, and The result { a: { b: 'hello', d: 'e' } }
will not be obtained. This is usually not what developers want and requires special care.
Some function libraries provide customized versions of Object.assign
(such as the _.defaultsDeep
method of Lodash
), which can obtain deep copy merging .
(3) Array processingObject.assign
can be used to process arrays, but the array will be 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, 2
, so the source array is 0# The ## attribute
4 overwrites the
0 attribute
1 of the target array.
(4) Processing of value functions
Object.assign can only copy values. If the value to be copied is a value value function, it will be evaluated and then copied.
const source = { get foo() { return 1 } } const target = {} Object.assign(target, source) // { foo: 1 }
foo attribute of the
source object is a value function,
Object.assign will not copy this value function , it will only copy the value after getting it.
Usage of Object.assign
The Object.assign method has many uses.
(1)为对象添加属性
class Point { constructor(x, y) { Object.assign(this, {x, y}) } }
上面方法通过Object.assign
方法,将x
属性和y
属性添加到Point
类的对象实例。
(2)为对象添加方法
Object.assign(SomeClass.prototype, { someMethod(arg1, arg2) { ··· }, anotherMethod() { ··· } }) // 等同于下面的写法 SomeClass.prototype.someMethod = function (arg1, arg2) { ··· } SomeClass.prototype.anotherMethod = function () { ··· }
上面代码使用了对象属性的简洁表示法,直接将两个函数放在大括号中,再使用assign
方法添加到SomeClass.prototype
之中。
(3)克隆对象
function clone(origin) { return Object.assign({}, origin) }
上面代码将原始对象拷贝到一个空对象,就得到了原始对象的克隆。
不过,采用这种方法克隆,只能克隆原始对象自身的值,不能克隆它继承的值。如果想要保持继承链,可以采用下面的代码。
function clone(origin) { let originProto = Object.getPrototypeOf(origin) return Object.assign(Object.create(originProto), origin) }
(4)合并多个对象
将多个对象合并到某个对象。
const merge = (target, ...sources) => Object.assign(target, ...sources)
如果希望合并后返回一个新对象,可以改写上面函数,对一个空对象合并。
const merge = (...sources) => Object.assign({}, ...sources)
(5)为属性指定默认值
const DEFAULTS = { logLevel: 0, outputFormat: 'html' } function processContent(options) { options = Object.assign({}, DEFAULTS, options) console.log(options) // ... }
上面代码中,DEFAULTS
对象是默认值,options
对象是用户提供的参数。Object.assign
方法将DEFAULTS
和options
合并成一个新对象,如果两者有同名属性,则option
的属性值会覆盖DEFAULTS
的属性值。
注意:由于存在浅拷贝的问题,DEFAULTS
对象和options
对象的所有属性的值,最好都是简单类型,不要指向另一个对象。否则,DEFAULTS
对象的该属性很可能不起作用。
const DEFAULTS = { url: { host: 'example.com', port: 7070 }, } processContent({ url: {port: 8000} }) // { // url: {port: 8000} // }
上面代码的原意是将 url.port
改成 8000
,url.host
不变。实际结果却是options.url
覆盖掉DEFAULTS.url
,所以url.host
就不存在了。
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of Is assign an es6 method?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

No, require is the modular syntax of the CommonJS specification; and the modular syntax of the es6 specification is import. require is loaded at runtime, and import is loaded at compile time; require can be written anywhere in the code, import can only be written at the top of the file and cannot be used in conditional statements or function scopes; module attributes are introduced only when require is run. Therefore, the performance is relatively low. The properties of the module introduced during import compilation have slightly higher performance.

The map is ordered. The map type in ES6 is an ordered list that stores many key-value pairs. The key names and corresponding values support all data types; the equivalence of key names is determined by calling the "Objext.is()" method. Implemented, so the number 5 and the string "5" will be judged as two types, and can appear in the program as two independent keys.
