ECMAScript 6箭头功能 [英] ECMAScript 6 arrow functions

查看:140
本文介绍了ECMAScript 6箭头功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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"
   };
};

但是我对以下

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?

推荐答案

ES6的几个语法糖元素在这里播放:

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


  • 参数解构:该函数实际上需要一个对象,但是在函数执行之前,其唯一的对象参数被解构为三个变量。基本上,如果传递给函数的参数被称为obj,那么onClick变量被赋值为obj.onClick,与其他命名的destructure变量相同。

  • 简明箭头体:只需要一个表达式的箭头函数就可以使用简洁的表单。例如,x => 2 * x是一个箭头函数,返回其输入时间2。然而,ES6语法规范说,箭头后面的大括号必须被解释为语句块。所以为了使用一个简洁的正文返回一个对象,你必须将对象表达式包含在括号中。

  • JSX :在JSX表达式中常用括号需要跨越多行。

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

奖励:箭头函数与函数声明和函数表达式不同的一种方式是事实上,在一个箭头函数(即使是一个不简洁的正文)中,参数这个的值是与包含范围相同。所以调用带有 .call .apply 的箭头函数没有任何效果,你需要使用休息参数if你希望你的箭头函数采用可变数量的参数。

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.

这篇关于ECMAScript 6箭头功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆