对象传播与Object.assign [英] Object spread vs. 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?
使用对象传播
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.)
不那么详细。
-
A 提案,不标准化。 (考虑一下你现在写的是什么,它没有标准化。)
A proposal, not standardized. (Consider what you'd do if you write it now and it doesn't get standardized.)
文字,而非动态。
options = Object.assign({}, optionsDefault, options);
优点:
-
标准化。
Advantages:
Standardized.
动态。示例:
var sources = [{a: "A"}, {b: "B"}, {c: "C"}]; options = Object.assign.apply(Object, [{}].concat(sources));
-
更详细。
More verbose.
- 如果在没有原生支持的环境中执行创作代码,则需要填充。
这是让我惊讶的提交。
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 includeobject-assign
as a dependency that would go into their build.这篇关于对象传播与Object.assign的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-