Is assign an es6 method?

青灯夜游
Release: 2022-03-23 14:52:26
Original
1896 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!