问题
So to my understanding which is obviously wrong at this moment in time is that,
return arg => arg*2
is the same as
return (arg)=>{arg*2}
I always assumed arrow functions are just syntactically neater.
But doing this with closures like so doesn't work.
function addTwoDigits(firstDigit){
return (secondDigit)=>{firstDigit + secondDigit}
}
let closure = addTwoDigits(5);
console.log(closure(5)) // Undefined
Yet this is fine
function addTwoDigitsV2(firstDigit){
return secondDigit => firstDigit + secondDigit
}
let closure2 = addTwoDigitsV2(10);
console.log(closure2(10))// 20
回答1:
arrow function works differently here:-
(x)=> x*2 ; // dont have to return anything, x*2 will be returned
is not same as
(x) =>{x*2}
//here you need to return something otherwise undefined will be returned
回答2:
When you use {} you must set return
return (arg)=>{return arg*2}
回答3:
You need a return
statement if the body of your arrow function is wrapped in {
... }
.
Since yours is a single expression, you can skip the {
-}
and return
. But if you have the {
-}
, you need the return
statement.
The parentheses are not an issue here. You need them if you have more than a single parameter. With one, they're optional.
回答4:
The arrow function only supplies the return
automatically if you have an expression after the arrow. If the arrow is followed by a curly brace, it's treated as the braces around a function body, so you have to write return
explicitly, i.e.
arg => arg * 2
is equivalent to:
(arg) => { return arg * 2; }
function addTwoDigits(firstDigit) {
return (secondDigit) => {
return firstDigit + secondDigit
}
}
let closure = addTwoDigits(5);
console.log(closure(5))
来源:https://stackoverflow.com/questions/51901683/closures-and-arrow-syntax