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:
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.
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.