扩展操作符与Object.assign [英] Spread operator vs Object.assign

查看:194
本文介绍了扩展操作符与Object.assign的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个选项变量,我想设置一些默认值。



这两个选项的优点/缺点是什么?



使用扩展运算符

  options = {... optionsDefault,... options }; 

或使用Object.assign

  options = Object.assign({},optionsDefault,options); 

这是提交,这让我很奇怪。

解决方案

这不一定是详尽无遗的。

传播语法



  options = {... optionsDefault,... options}; 



优点:




  • 如果在没有本机支持的环境中执行代码编写,您可能只需编译此语法(而不是使用polyfill)。 (以Babel为例)


  • 较少详细




缺点:




  • A 提案,不规范。 (请考虑你现在写什么,并且没有标准化)。


  • 文字,而不是动态。







Object.assign()



  options = Object.assign({},optionsDefault,options); 



优点:




  • 标准化。


  • 动态。例如:

      var sources = [{a:A},{b:B },{c:C}]; 
    options = Object.assign.apply(Object,[{}]。concat(sources));


  • 更详细。




缺点:




  • 如果在没有本地支持的环境中执行的创作代码,则需要进行polyfill







这是让我想知道的提交


这与您所要求的不直接相关。该代码没有使用 Object.assign(),它使用的是用户代码( object-assign )一样的东西。他们似乎正在使用Babel编译代码(并将其与Webpack捆绑在一起),这正是我所说的:您可以编译的语法。他们显然希望不得不将 object-assign 作为依赖关系,进入他们的构建。


Let's say I have an options variable and I want to set some default value.

What's is the benefit / drawback of these two alternatives?

Use the spread operator

options = {...optionsDefault, ...options};

Or use Object.assign

options = Object.assign({}, optionsDefault, options);

This is the commit that made me wonder.

解决方案

This isn't necessarily exhaustive.

Spread syntax

options = {...optionsDefault, ...options};

Advantages:

  • If authoring code for execution in environments without native support, you may be able to just compile this syntax (as opposed to using a polyfill). (With Babel, for example.)

  • Less verbose.

Disadvantages:

  • A proposal, not standardized. (Consider what you'd do if you write it now and it doesn't get standardized.)

  • Literal, not dynamic.


Object.assign()

options = Object.assign({}, optionsDefault, options);

Advantages:

  • Standardized.

  • Dynamic. Example:

    var sources = [{a: "A"}, {b: "B"}, {c: "C"}];
    options = Object.assign.apply(Object, [{}].concat(sources));
    

  • More verbose.

Disadvantages:

  • If authoring code for execution in environments without native support you need to polyfill.

This is the commit that made me wonder.

That's not directly related to what you're asking. That code wasn't using Object.assign(), it was using user code (object-assign) that does the same thing. They appear to be compiling that code with Babel (and bundling it with Webpack), which is what I was talking about: the syntax you can just compile. They apparently preferred that to having to include object-assign as a dependency that would go into their build.

这篇关于扩展操作符与Object.assign的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆