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
224 views
in Technique[技术] by (71.8m points)

javascript - ECMAScript 6 arrow functions

var getTempItem = id => ({ id: id, name: "Temp" });

I know the above arrow function is equivalent to:

var getTempItem = function(id) {

    return {
        id: id,
        name: "Temp"
   };
};

But I'm a bit confused about the following

const Todo = ({ onClick, completed, text }) => (
  <li
    onClick={onClick}
    style={{
      textDecoration: completed ? 'line-through' : 'none'
    }}
  >
    {text}
 </li>
)

Why are the function arguments wrapped in curly braces, and the the function body is wrapped only in parentheses?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

A few syntactic sugar elements of ES6 are at play here:

  • Parameter destructuring: The function actually takes one object, but before the function is executed, its sole object parameter is deconstructed into three variables. Basically, if the argument passed to the function is called obj, then the onClick variable is assigned the value of obj.onClick, and same with the other named destructure variables.
  • Concise arrow bodies: An arrow function that only needs one expression can use the concise form. For example, x => 2*x is an arrow function that returns its input times two. However, the ES6 grammar specification says that a curly brace after the arrow must be interpreted as a statement block. So in order to return an object using a concise body, you have to wrap the object expression in parentheses.
  • JSX: Parentheses are commonly used around JSX expressions that need to span more than one line.

Bonus: One manner in which arrow functions are different from function declarations and function expressions is in the fact that in an arrow function (even one with a non-concise body), the values of arguments and this are the same as the containing scope. So calling an arrow function with .call or .apply will have no effect, and you need to use rest parameters if you want your arrow function to take a variable number of arguments.


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

...