assign复制对象
Introduced in ES2015
, this method copies all the enumerable own properties of one or more objects into another.
此方法在ES2015
中ES2015
,将一个或多个对象的所有可枚举的自身属性复制到另一个对象中。
Its primary use case is to create a shallow copy of an object.
它的主要用例是创建对象的浅表副本。
const copied = Object.assign({}, original)
Being a shallow copy, values are cloned, and objects references are copied (not the objects themselves), so if you edit an object property in the original object, that’s modified also in the copied object, since the referenced inner object is the same:
作为浅表副本,将克隆值并复制对象引用(而不是对象本身),因此,如果在原始对象中编辑对象属性,则在复制的对象中也将对其进行修改,因为引用的内部对象是相同的:
const original = {
name: 'Fiesta',
car: {
color: 'blue'
}
}
const copied = Object.assign({}, original)
original.name = 'Focus'
original.car.color = 'yellow'
copied.name //Fiesta
copied.car.color //yellow
I mentioned “one or more”:
我提到“一个或多个”:
const wisePerson = {
isWise: true
}
const foolishPerson = {
isFoolish: true
}
const wiseAndFoolishPerson = Object.assign({}, wisePerson, foolishPerson)
console.log(wiseAndFoolishPerson) //{ isWise: true, isFoolish: true }
assign复制对象