闭包和箭头语法 [英] Closures and arrow syntax

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

问题描述

据我所知,这时显然是错误的,

So to my understanding which is obviously wrong at this moment in time is that,

return arg => arg*2

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

这还好

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

推荐答案

箭头功能在这里的工作方式有所不同:-

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

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

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