Home Web Front-end Front-end Q&A Is assign an es6 method?

Is assign an es6 method?

Mar 23, 2022 pm 02:52 PM
assign es6

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.

Is assign an es6 method?

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 }
Copy after login

Object.assignThe 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}
Copy after login

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
Copy after login

If the parameter is not an object, it will be converted into an object first and then returned.

typeof Object.assign(2) // "object"
Copy after login

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) // 报错
Copy after login

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
Copy after login

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" }
Copy after login

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"}
Copy after login

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.assignThe 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' }
Copy after login

In the above code, Object.assignThe 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' }
Copy after login

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
Copy after login

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' } }
Copy after login

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]
Copy after login

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 }
Copy after login

In the above code, the

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})
  }
}
Copy after login

上面方法通过Object.assign方法,将x属性和y属性添加到Point类的对象实例。

(2)为对象添加方法

Object.assign(SomeClass.prototype, {
  someMethod(arg1, arg2) {
    ···
  },
  anotherMethod() {
    ···
  }
})

// 等同于下面的写法
SomeClass.prototype.someMethod = function (arg1, arg2) {
  ···
}
SomeClass.prototype.anotherMethod = function () {
  ···
}
Copy after login

上面代码使用了对象属性的简洁表示法,直接将两个函数放在大括号中,再使用assign方法添加到SomeClass.prototype之中。

(3)克隆对象

function clone(origin) {
  return Object.assign({}, origin)
}
Copy after login

上面代码将原始对象拷贝到一个空对象,就得到了原始对象的克隆。

不过,采用这种方法克隆,只能克隆原始对象自身的值,不能克隆它继承的值。如果想要保持继承链,可以采用下面的代码。

function clone(origin) {
  let originProto = Object.getPrototypeOf(origin)
  return Object.assign(Object.create(originProto), origin)
}
Copy after login

(4)合并多个对象

将多个对象合并到某个对象。

const merge = (target, ...sources) => Object.assign(target, ...sources)
Copy after login

如果希望合并后返回一个新对象,可以改写上面函数,对一个空对象合并。

const merge = (...sources) => Object.assign({}, ...sources)
Copy after login

(5)为属性指定默认值

const DEFAULTS = {
  logLevel: 0,
  outputFormat: 'html'
}

function processContent(options) {
  options = Object.assign({}, DEFAULTS, options)
  console.log(options)
  // ...
}
Copy after login

上面代码中,DEFAULTS对象是默认值,options对象是用户提供的参数。Object.assign方法将DEFAULTSoptions合并成一个新对象,如果两者有同名属性,则option的属性值会覆盖DEFAULTS的属性值。

注意:由于存在浅拷贝的问题,DEFAULTS对象和options对象的所有属性的值,最好都是简单类型,不要指向另一个对象。否则,DEFAULTS对象的该属性很可能不起作用。

const DEFAULTS = {
  url: {
    host: 'example.com',
    port: 7070
  },
}

processContent({ url: {port: 8000} })
// {
//   url: {port: 8000}
// }
Copy after login

上面代码的原意是将 url.port改成 8000url.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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to reverse an array in ES6 How to reverse an array in ES6 Oct 26, 2022 pm 06:19 PM

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()".

Is async for es6 or es7? Is async for es6 or es7? Jan 29, 2023 pm 05:36 PM

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.

Why does the mini program need to convert es6 to es5? Why does the mini program need to convert es6 to es5? Nov 21, 2022 pm 06:15 PM

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.

How to find different items in two arrays in es6 How to find different items in two arrays in es6 Nov 01, 2022 pm 06:07 PM

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)".

How to implement array deduplication in es5 and es6 How to implement array deduplication in es5 and es6 Jan 16, 2023 pm 05:09 PM

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.

What does es6 temporary Zenless Zone Zero mean? What does es6 temporary Zenless Zone Zero mean? Jan 03, 2023 pm 03:56 PM

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.

Is require an es6 syntax? Is require an es6 syntax? Oct 21, 2022 pm 04:09 PM

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.

Is es6 map ordered? Is es6 map ordered? Nov 03, 2022 pm 07:05 PM

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.

See all articles