Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

javascript - Is application of the ES6 spread operator on Objects a standard ECMAScript specification?

MDN defines the usage of the spread operator as acting for arrays only.

For example, a proper usage for the spread operator looks like

var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes']; // ["head", "shoulders", "knees", "and", "toes"]

where we have applied the spread operator on the array parts.

But in the React docs, they use the spread operator on objects like so

var props = {}; 
props.foo = x; 
props.bar = y; 
var component = <Component {...props} />;

If I actually try to do this in the console, I receive a TypeError

var a = {b:1,c:2}
console.log(...a);  // TypeError

My questions are:

  • Is using the spread operator over objects a standard implemented in the spec (and this use case was somehow omitted from the MDN docs and the console example I tried to show was not done correctly thus giving the TypeError)?
  • If not a standard implementation, what is going on under the hood to allow the React component to finesse the spread operator to act in the non-standard method that it does (i.e. acting on objects), and suppress the TypeError that would inevitably arise when doing so?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I actually try to do this in the console, I receive a TypeError

You are confusing some things here (can't blame you if they all look similar).

In your example,

console.log(...a);

the ...a is not an application of object spread. It's sometimes referred to as spread syntax (even though this one specifically doesn't really have a name), which is standardized in ES2015. It is used in function calls as last "argument" and only works on iterables. Objects are not iterables and hence you get the error.

Object spread, which currently is a proposal, is only used in object literals:

var foo = {x: 42};
var bar = {y: 21, ...foo}; // equivalent to Object.assign({y: 21}, foo);

what is going on under the hood

The use inside JSX (<Component {...props} />) is a again something slightly different, its a JSXSpreadAttribute, but it does desugar to object spread. If you try it out in Babel you can see what it is converted to:

var _extends = Object.assign || /* polyfill */;

React.createElement(Component, _extends({ foo: true }, props));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...