声明后是否有一种方法可以调用Arrow函数?

时间:2019-01-28 11:10:22

标签: javascript ecmascript-6 arrow-functions

有时我想为Arrow函数的结果分配一个变量,但是如果我将Arrow Function分配给该变量,它将得到该函数,而不是显而易见的该函数的返回。

let theNumber2 = ()=>{return 2};

theNumber2将包含该函数,并且只有在执行theNumber2()时我才会返回2。

有没有一种方法可以像这样直接获得箭头函数的返回值?例如:

let theNumber2 = ()=>{return 2}(); // Note the () at the final

是否存在要做的事情?我的意思是,要分配调用的箭头功能?

1 个答案:

答案 0 :(得分:9)

只需换行并调用函数即可。

let theNumber2 = (() => { return 2; })();

console.log(theNumber2);