Obejct.assign的使用以及和rest扩展运算符的区别

Object.assign()

  1. copy第一层,引用对象copy地址

    1. 浅克隆(不克隆原型链

      function clone(origin) {
        return Object.assign({}, origin);
      }
      
    2. 保持原型链

      function clone(origin) {
        let originProto = Object.getPrototypeOf(origin);
        return Object.assign(Object.create(originProto), origin);
      }
      
  2. 会触发setter

    这使得mutation的值发生改变,这在vue中批量更新不带引用的数据的属性的时候可以起到效果。一般是同名属性替换操作。写法参考5.1例子。

    class MyClass {
        set val(v) {
            console.log('Setter called', v);
            return v;
        }
    }
    
    const obj = new MyClass();
    
    Object.assign(obj,  { val:  42  }); // console Setter called 42
    
    {...obj, ...{val: 42}}; // console nothing
    
  3. 添加属性

    class Point {
      constructor(x, y) {
        Object.assign(this, {x, y});
      }
    }
    
  4. 添加方法

    Object.assign(SomeClass.prototype, {
      someMethod(arg1, arg2) {
        ···
      },
      anotherMethod() {
        ···
      }
    });
    
    // 等同于下面的写法
    SomeClass.prototype.someMethod = function (arg1, arg2) {
      ···
    };
    SomeClass.prototype.anotherMethod = function () {
      ···
    };
    
  5. 合并对象

    1. 同名属性替换

      const target = { a: { b: 'c', d: 'e' } }
      const source = { a: { b: 'hello' } }
      Object.assign(target, source)
      // { a: { b: 'hello' } }
      
    2. Object.assign只能进行值的复制,如果要复制的值是一个取值函数,那么将求值后再复制。

      const source = {
        get foo() { return 1 }
      };
      const target = {};
      
      Object.assign(target, source)
      // { foo: 1 } // 赋值了值,没有方法
      
    3. 合并到某个对象

      const merge = (target, …sources) => Object.assign(target, …sources)

      let data = {a: 1, b: 2}

      let info = {}

      merge(info, data)

    4. 合并成一个新对象

      const merge = (…sources) => Object.assign({}, …sources)

      let data = {a: 1, b: 2}

      let info = {}

      info = merge(data)

  6. 默认值合并

    const DEFAULTS = {
      logLevel: 0,
      outputFormat: 'html'
    };
    
    function processContent(options) {
      options = Object.assign({}, DEFAULTS, options);
      console.log(options);
      // ...
    }
    

… 扩展运算符,基本情况同Object.assign()

区别是:不会触发setter。也就是说如果对象是监听setter然后执行回调的话,这个操作是不会触发对象的更新监听的。

代码更简洁,据说性能也更高。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值