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
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools