本篇文章為大家帶來了關於javascript的相關知識,其中主要介紹了箭頭函數應用的相關問題,箭頭函數表達式更適用於那些本來需要匿名函數的地方,並且它不能用作構造函數,下面一起來看一下,希望對大家有幫助。
【相關推薦:javascript影片教學、web前端】
##簡介箭頭函數表達式的語法比函數表達式更簡潔,也沒有自己的this,arguments,super或new.target。箭頭函數表達式更適用於那些本來需要匿名函數的地方,並且它不能用作構造函數。 ---- MDN基礎用法
(param1, param2, …, paramN) => { statements } (param1, param2, …, paramN) => expression //相当于:(param1, param2, …, paramN) =>{ return expression; } // 当只有一个参数时,圆括号是可选的: (singleParam) => { statements } singleParam => { statements } // 没有参数的函数应该写成一对圆括号。 () => { statements }
let add1 = (num1, num2) => { num1 + num2 }; let add2 = (num1, num2) => { return num1 + num2 }; let add3 = (num1, num2) => (num1 + num2); let add4 = (num1, num2) => num1 + num2; console.log(add1(2, 3)); // undefined console.log(add2(2, 3)); // 5 console.log(add3(2, 3)); // 5 console.log(add4(2, 3)); // 5
//加括号的函数体返回对象字面量表达式: let func = () => ({foo: 'bar'}) console.log(func()); // {foo: 'bar'} //支持剩余参数和默认参数 (param1, param2, ...rest) => { statements } (param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements } //同样支持参数列表解构 let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; f(); // 6
如果函數邏輯相當複雜,應使用命名函數
why?語法更簡潔,並且this更符合預期
// bad[1, 2, 3].map(function (x) { const y = x + 1; return x * y;});// good[1, 2, 3].map((x) => { const y = x + 1; return x * y;});
// bad [1, 2, 3].map(number => { const nextNumber = number + 1; `A string containing the ${nextNumber}.`; }); // good [1, 2, 3].map(number => `A string containing the ${number}.`); // good [1, 2, 3].map((number) => { const nextNumber = number + 1; return `A string containing the ${nextNumber}.`; }); // good [1, 2, 3].map((number, index) => ({ [index]: number, })); // No implicit return with side effects function foo(callback) { const val = callback(); if (val === true) { // Do something if callback returns true } } let bool = false; // bad foo(() => bool = true); // good foo(() => { bool = true; });
#why?函數開頭和結束更明確
// bad['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call( httpMagicObjectWithAVeryLongName, httpMethod, ));// good['get', 'post', 'put'].map(httpMethod => ( Object.prototype.hasOwnProperty.call( httpMagicObjectWithAVeryLongName, httpMethod, )));
// bad[1, 2, 3].map((x) => x * x);// good[1, 2, 3].map(x => x * x);// good[1, 2, 3].map(number => ( `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`));// bad[1, 2, 3].map(x => { const y = x + 1; return x * y;});// good[1, 2, 3].map((x) => { const y = x + 1; return x * y;});
// badconst itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize;// badconst itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize;// goodconst itemHeight = item => (item.height > 256 ? item.largeSize : item.smallSize);// goodconst itemHeight = (item) => { const { height, largeSize, smallSize } = item; return height > 256 ? largeSize : smallSize;
以上是實例程式碼之ES6箭頭函數實踐的詳細內容。更多資訊請關注PHP中文網其他相關文章!