闭包和箭头语法

Mun*_*erz -2 javascript closures arrow-functions

所以据我所知,此时此刻显然是错误的,

return arg => arg*2
Run Code Online (Sandbox Code Playgroud)

是相同的

return (arg)=>{arg*2}
Run Code Online (Sandbox Code Playgroud)

我一直认为箭头函数在语法上更简洁。

但是用像这样的闭包来做这件事是行不通的。

function addTwoDigits(firstDigit){
    return (secondDigit)=>{firstDigit + secondDigit}
}
let closure = addTwoDigits(5);
console.log(closure(5)) // Undefined
Run Code Online (Sandbox Code Playgroud)

然而这很好

function addTwoDigitsV2(firstDigit){
    return secondDigit => firstDigit + secondDigit
}
let closure2 = addTwoDigitsV2(10);
console.log(closure2(10))// 20
Run Code Online (Sandbox Code Playgroud)

小智 6

箭头函数在这里的工作方式不同:-

(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
Run Code Online (Sandbox Code Playgroud)


小智 5

当您使用 {} 时,您必须设置 return

return (arg)=>{return arg*2}
Run Code Online (Sandbox Code Playgroud)