[英]What's the correct syntax for a named arrow function registered as callback?
[英]What is the correct arrow function syntax?
箭頭函數可以用很多不同的方式編寫,有沒有“更正確”的方式?
let fun1 = (a) => { return a; }
let fun2 = a => a;
就像上面的那些情況一樣,fun2 比 fun1 快嗎? 他們之間有什么區別?
箭頭函數可以用一些不同的方式編寫,如下所示:
// No params, just returns a string
const noParamsOnlyRet = () => 'lul';
// No params, no return
const noParamsNoRet = () => { console.log('lul'); };
// One param, it retuns what recives
const oneParamOnlyRet = a => a;
// Makes the same thing that the one above
const oneParamOnlyRet2 = a => { return a; };
// Makes the same thing that the one above
const oneParamOnlyRet3 = (a) => a;
/* Makes the same thing that the one above, parentheses in return are optional,
* only needed if the return have more then one line, highly recomended put
* objects into parentheses.
*/
const oneParamOnlyRet4 = (a) => (a);
// Mult params, it returns the sum
const multParamsOnlyRet = (a, b) => a + b;
// Makes the same thing that the one above
const multParamsOnlyRet2 = (a, b) => { return a + b; }
// Curly brackets are needed in multiple line arrow functions
const multParamsMultLines = (a, b) => {
let c = a + b;
return c;
}
所以我們有一些規則:
return
可以省略,如果它適合一行如您所見,所有這些都是箭頭函數的有效語法,它們中沒有一個比另一個更快,您使用哪一個取決於您的編碼方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.