Object.assign深浅拷贝


Object.assign深浅拷贝

Object.assign拷贝的 ***属性值为简单类型时为深拷贝、拷贝的 ***属性值为对象时,为浅拷贝。

  let obj1 = { name: 'Eric' }
  let obj2 = { list: ['Rose', 'Jack'] }

  let obj3 = Object.assign({}, obj1, obj2) 
  console.log('obj3', obj3) // obj3 {name: 'Eric', list: Array(2)}


  console.log('-'.repeat(30))
  obj3.list.push('Lucy')

  console.log('push后', obj3) // list: (3) ['Rose', 'Jack', 'Lucy']
                              // name: "666"
  console.log('push后obj2变没变', obj2) // list: (3) ['Rose', 'Jack', 'Lucy'] 发现obj2也变了
  console.log('-'.repeat(30))


  obj3.name = '666'
  console.log('看第一个name改变后的obj3', obj3) // name: "666"
  console.log('看第一个name改变后的obj1', obj1) // name: "Eric" 简单数据类型没变!




  console.log('-'.repeat(30))
  let obj4 = { one: { name: '牛恒' } }
  let obj5 = { two: { name: 'nnn' } }
  let obj6 = Object.assign({}, obj4, obj5)
  console.log('obj6', obj6) // {one: {…}, two: {…}}
  obj6.one.name = '牛逼'
  console.log('change', obj6) // one: {name: '牛逼'}
                              // two: {name: 'nnn'}
  console.log('看是否对obj4有影像', obj4) // one: {name: '牛逼'}  发现obj6 改变, obj4也改变了

文章作者: KarlFranz
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 reprint policy. If reproduced, please indicate source KarlFranz !
评论
  目录