对象传播与 Object.assign [英] Object spread vs. Object.assign

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

问题描述

假设我有一个 options 变量,我想设置一些默认值.

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?

使用对象传播

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

或者使用 Object.assign

Or using Object.assign

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

这是让我感到惊奇的提交.

推荐答案

这不一定是详尽无遗的.

This isn't necessarily exhaustive.

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

优点:

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

    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.)

      不那么冗长.

      • 最初编写此答案时,这是一个提案,而不是标准化.在使用提案时,请考虑如果您现在用它编写代码并且在朝着标准化方向发展时它不会变得标准化或变化,您会怎么做.这已在 ES2018 中标准化.

      • When this answer was originally written, this was a proposal, not standardized. When using proposals consider what you'd do if you write code with it now and it doesn't get standardized or changes as it moves toward standardization. This has since been standardized in ES2018.

      文字,而非动态.

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

      优点:

      • 标准化.

        Advantages:

        • Standardized.

          动态.示例:

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

          • 更详细.
          • 如果编写代码以在没有本机支持的环境中执行,您需要进行 polyfill.

          这是让我感到惊奇的提交.

          This is the commit that made me wonder.

          这与您的要求没有直接关系.该代码没有使用 Object.assign(),而是使用了用户代码 (object-assign) 来做同样的事情.他们似乎在用 Babel 编译代码(并用 Webpack 捆绑它),这就是我所说的:你可以编译的语法.他们显然更愿意将 object-assign 作为依赖项包含在他们的构建中.

          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天全站免登陆