有没有办法在声明之后调用箭头函数?

Smo*_*_js 3 javascript ecmascript-6 arrow-functions

有时我想为一个变量分配一个箭头函数的结果,但是如果我将箭头函数分配给该变量,它就会得到函数而不是该函数的返回,这是显而易见的.

let theNumber2 = ()=>{return 2};
Run Code Online (Sandbox Code Playgroud)

theNumber2将包含该功能,只有我这样做theNumber2()才会返回2.

有没有办法做这样的事情直接返回箭头功能?例如:

let theNumber2 = ()=>{return 2}(); // Note the () at the final
Run Code Online (Sandbox Code Playgroud)

有没有可做的事情?我的意思是,分配箭头函数调用?

Nin*_*olz 10

只需括在括号中并调用该函数即可.

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

console.log(theNumber2);
Run Code Online (Sandbox Code Playgroud)

  • 旁注:`让theNumber2 =(()=> 2)();`;-) (3认同)