Object.assign()

138 阅读1分钟

Object.assign(target,…sources)合并对象(浅拷贝)

target -- 目标对象
sources -- 源对象
返回目标对象
  • 如果目标对象与源对象有同名属性,或多个源对象有同名属性,则后面的属性会覆盖前面的属性
let obj1 = {uname: '123',age:10}
let obj2 = {age:18}
let obj4 = Object.assign(obj1,obj2,);
console.log(obj4) // {uname: "123", age: 18}
  • 如果只有一个目标对象参数,Object.assign()直接返回 Object.assign(obj) === obj // true
  • 如果只有一个目标对象参数且不是对象,会转为对象 Object.assign(2) // {2}
  • 如果目标对象为null和undefined无法转为对象,会报错 ````
  • Object.assign()的拷贝是有限制的,只拷贝源对象的自身属性(不拷贝继承属性,也不拷贝不可枚举的属性)
  • Object.assign()方法实行的是浅拷贝
let obj1 = {uname: '123',age:10}
let obj2 = {age:18}
let obj4 = Object.assign(obj1,obj2,);
obj4.uname = 'chen'; 
console.log(obj1,obj4,obj1 === obj4); // 都为{uname: "chen", age: 18} true 证明为浅拷贝
  • 深拷贝思路,将源对象当做我们要深拷贝的对象,目标对象为{}
let sources = { one:'one' }
let sources1 = Object.assign({},sources)
sources.two = 'two'
sources1.three = 'three'
console.log(sources,sources1,sources == sources1) 
// {one: "one", two: "two"} {one: "one", three: "three"} false 深拷贝
  • 如果源对象的层级超过1层,对于超过的层级来说是还是浅拷贝
let man = { key: { age: '10' } , one:'one'}
let women = Object.assign({}, man)
man.key.age = 24 // 此还是浅拷贝
man.one = '修改one' // 此为深拷贝
console.log(man , women,man == women) 
  • 特殊写法
Object.assign(this,{id:"0"})
console.log(this.id) // "0"
function fn(date = new Date()){
    this.date = new Date(date)
    this.year = this.date.getFullYear()
}
Object.assign(fn.prototype,{
    onf(){ return "今年是" + this.year + "年" }
})
const dateFactory = new fn()
console.log(dateFactory.onf()) // "今年是2022年"