[英]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? 为什么函数参数用大括号括起来,而函数主体仅用括号括起来?
A few syntactic sugar elements of ES6 are at play here: ES6的一些语法糖元素在这里起作用:
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. 奖金:其中箭头功能是从函数声明和函数表达式不同的一种方式是在一个事实,即在箭头功能(甚至用非简明体),的值
arguments
和this
是相同的包含范围内。 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. 所以调用带有箭头的功能
.call
或.apply
不会有任何效果,你需要的,如果你希望你的箭头功能可以带可变数量的参数,使用其余的参数。
Function body wrapped in parentheses returns the value of expression wrapped in parentheses. 括在括号中的函数体返回括在括号中的表达式的值。
var getTempItem = id => ({ id: id, name: "Temp" });
var getTempItem = id => {return { id: id, name: "Temp" }};
// Identical
Showing it with an example. 举例说明。
Parameter Destructuring: 参数解构:
Here you can see that while logEmployee function is taking in two parameters, we are only passing in the employee object as a part of the code. 在这里您可以看到,虽然logEmployee函数使用两个参数,但我们只是将employee对象作为代码的一部分传入。 We are not passing individual parameters.
我们没有传递单个参数。 So at runtime the employee object's contents are extracted to match the params that the function is expecting and are passed in accordingly.
因此,在运行时,将提取员工对象的内容以匹配该函数期望的参数,并相应地将其传递。
const employee = {
id: 1,
name: "John",
age: 28
}
const logEmployee = ({name, age}) => (
console.log(name, age)
)
logEmployee(employee);
Note that only name and age are required by the function, so only those two properties will be destructured from the employee object. 请注意,该功能仅需要名称和年龄,因此只有这两个属性将从雇员对象中解构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.