search
HomeWeb Front-endFront-end Q&AIs assign an es6 method?

Is assign an es6 method?

Mar 23, 2022 pm 02:52 PM
assignes6

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 }

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}

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.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' }

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' }

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 }

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})
  }
}

上面方法通过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方法将DEFAULTSoptions合并成一个新对象,如果两者有同名属性,则option的属性值会覆盖DEFAULTS的属性值。

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

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

processContent({ url: {port: 8000} })
// {
//   url: {port: 8000}
// }

上面代码的原意是将 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
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
HTML and React's Integration: A Practical GuideHTML and React's Integration: A Practical GuideApr 21, 2025 am 12:16 AM

HTML and React can be seamlessly integrated through JSX to build an efficient user interface. 1) Embed HTML elements using JSX, 2) Optimize rendering performance using virtual DOM, 3) Manage and render HTML structures through componentization. This integration method is not only intuitive, but also improves application performance.

React and HTML: Rendering Data and Handling EventsReact and HTML: Rendering Data and Handling EventsApr 20, 2025 am 12:21 AM

React efficiently renders data through state and props, and handles user events through the synthesis event system. 1) Use useState to manage state, such as the counter example. 2) Event processing is implemented by adding functions in JSX, such as button clicks. 3) The key attribute is required to render the list, such as the TodoList component. 4) For form processing, useState and e.preventDefault(), such as Form components.

The Backend Connection: How React Interacts with ServersThe Backend Connection: How React Interacts with ServersApr 20, 2025 am 12:19 AM

React interacts with the server through HTTP requests to obtain, send, update and delete data. 1) User operation triggers events, 2) Initiate HTTP requests, 3) Process server responses, 4) Update component status and re-render.

React: Focusing on the User Interface (Frontend)React: Focusing on the User Interface (Frontend)Apr 20, 2025 am 12:18 AM

React is a JavaScript library for building user interfaces that improves efficiency through component development and virtual DOM. 1. Components and JSX: Use JSX syntax to define components to enhance code intuitiveness and quality. 2. Virtual DOM and Rendering: Optimize rendering performance through virtual DOM and diff algorithms. 3. State management and Hooks: Hooks such as useState and useEffect simplify state management and side effects handling. 4. Example of usage: From basic forms to advanced global state management, use the ContextAPI. 5. Common errors and debugging: Avoid improper state management and component update problems, and use ReactDevTools to debug. 6. Performance optimization and optimality

React's Role: Frontend or Backend? Clarifying the DistinctionReact's Role: Frontend or Backend? Clarifying the DistinctionApr 20, 2025 am 12:15 AM

Reactisafrontendlibrary,focusedonbuildinguserinterfaces.ItmanagesUIstateandupdatesefficientlyusingavirtualDOM,andinteractswithbackendservicesviaAPIsfordatahandling,butdoesnotprocessorstoredataitself.

React in the HTML: Building Interactive User InterfacesReact in the HTML: Building Interactive User InterfacesApr 20, 2025 am 12:05 AM

React can be embedded in HTML to enhance or completely rewrite traditional HTML pages. 1) The basic steps to using React include adding a root div in HTML and rendering the React component via ReactDOM.render(). 2) More advanced applications include using useState to manage state and implement complex UI interactions such as counters and to-do lists. 3) Optimization and best practices include code segmentation, lazy loading and using React.memo and useMemo to improve performance. Through these methods, developers can leverage the power of React to build dynamic and responsive user interfaces.

React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.