Object.assign的用法和注意点

Object.assign可以实现对象的合并。它的语法是这样的: Object.assign(target, ...sources)

Object.assign会将source里面的可枚举属性复制到target。如果和target的已有属性重名,则会覆盖。同时后续的source会覆盖前面的source的同名属性。

⚠️Object.assign复制的是属性值,如果属性值是一个引用类型,那么复制的其实是引用地址,就会存在引用共享的问题。

栗子:

obj1: {name: 'name1',age: 111},
obj2: {name: 'name2',sex: '男',favorite: ['ball', 'swim']},
obj3: {},

this.obj3 = Object.assign({}, this.obj1, this.obj2);
console.log('obj3', this.obj3);
//{age: 111,favorite: ['ball', 'swim'],name: 'name2',sex: '男'},

this.obj2.favarite.push('run')
console.log('obj3', this.obj3);
// {age: 111,favorite: ['ball', 'run', 'swim'],name: 'name2',sex: '男'},
console.log('obj2', this.obj2);
{name: 'name2',sex: '男',favorite: ['ball','run',  'swim']},
// ⚠️我们可以看到所有对象的topic值都被更新了

所以,想要使用Object.assign的时候,引用类型需要关注。

如果我们需要处理引用类型怎么办呢,这就涉及到对象的拷贝了,可以参考lodash的_clone, _cloneDeep等方法。

再附上MDN关于Object.assign的polyfill,方便大家理解内部实现,同时更好的掌握这个方法哟

if (typeof Object.assign != 'function') {
  Object.assign = function (target, varArgs) { // .length of function is 2
    'use strict';
    if (target == null) { // TypeError if undefined or null
      throw new TypeError('Cannot convert undefined or null to object');
    }

    var to = Object(target);

    for (var index = 1; index < arguments.length; index++) {
      var nextSource = arguments[index];

      if (nextSource != null) { // Skip over if undefined or null
        for (var nextKey in nextSource) {
          // Avoid bugs when hasOwnProperty is shadowed
          if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
    }
    return to;
  };
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hongc93

感谢鼓励 继续航行

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值