本文翻译自:Object spread vs. Object.assign
Let's say I have an options
variable and I want to set some default value. 假设我有一个options
变量,并且想要设置一些默认值。
What's is the benefit / drawback of these two alternatives? 这两种选择的优点/缺点是什么?
Using object spread 使用对象传播
options = {...optionsDefault, ...options};
Or using Object.assign 或使用Object.assign
options = Object.assign({}, optionsDefault, options);
This is the commit that made me wonder. 这就是让我感到奇怪的承诺 。
#1楼
参考:https://stackoom.com/question/2E9Po/对象传播与Object-assign
#2楼
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). 如果编写代码以在没有本机支持的环境中执行,则可以仅编译此语法(与使用polyfill相对)。 (With Babel, for example.) (例如,使用Babel。)
Less verbose. 不太冗长。
Disadvantages: 缺点:
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. 此后已在ES2018中标准化。
Literal, not dynamic. 从字面上看,不是动态