將以下傳統函式改寫成箭頭函式
1 2 3
| var callSomeone = function (someone) { return someone + '吃飯了'; }
|
箭頭函式
基本的箭頭函式寫法。
1 2 3
| var callSomeone = (someone) => { return someone + '吃飯了'; }
|
函式裡只有一行情況下,可以省略大括號和 return,和傳入參數的小括號,如果沒參數就要加小括號。
在 ESLint 的 Airbnb 規範裡,有無參數都要加小括號。
1
| var callSomeone = someone => someone + '吃飯了';
|
=> 等同於 return,少了 return,仍然能回傳值出來。
1
| console.log(callSomeone('小明')); // 小明吃飯了
|
arguments 參數
在使用傳統函式帶多個參數可讀出值來。
傳統函式:
1 2 3 4 5
| const updateEasyCard = function () { let cash = 0; console.log(arguments); // [ 10, 50, 100, 50, 5, 1, 1, 1, 500 ] } updateEasyCard(10, 50, 100, 50, 5, 1, 1, 1, 500);
|
但箭頭函式則跳出錯誤,原因是箭頭函式並沒有 arguments 變數。
箭頭函式:
1 2 3 4 5
| const updateEasyCard = () => { let cash = 0; console.log(arguments); // arguments is not defined } updateEasyCard(10, 50, 100, 50, 5, 1, 1, 1, 500);
|
如果要傳入多個值,就在小括號裡帶入其餘參數。
1 2 3 4 5
| const updateEasyCard = (...arg) => { let cash = 0; console.log(arg); // [ 10, 50, 100, 50, 5, 1, 1, 1, 500 ] } updateEasyCard(10, 50, 100, 50, 5, 1, 1, 1, 500);
|
This 綁定的差異
傳統函式的 this:
- 函式是從物件 auntie 去呼叫,所以 this 指向 auntie 物件。
- 函式裡的函式是指向 window,也就是 callName 裡的 setTimeout 是指向 window。
1 2 3 4 5 6 7 8 9 10 11 12
| var name = '全域阿婆' var auntie = { name: '漂亮阿姨', callName: function () { console.log('1', this.name); // 漂亮阿姨 setTimeout(function () { // 指向 window console.log('2', this.name); // 全域阿婆 console.log('3', this); // 全域 }, 10); }
auntie.callName();
|
箭頭函式的 this:
箭頭函式沒有自己的 This,因此它都是採用其同層級的 this 來作用。
意思是箭頭函式的 this 是指向箭頭函式定義時所在的環境,以下方範例來說:
- callName 定義在 auntie 物件中,取的是 auntie 物件的 this,全域。
- setTimeout 是取 callName 的 this,全域。
1 2 3 4 5 6 7 8 9 10 11
| var name = '全域阿婆' var auntie = { name: '漂亮阿姨', callName: () => { console.log('1', this.name); // 全域 setTimeout(() => { // 指向 window console.log('2', this.name); // 全域阿婆 console.log('3', this); // 全域 }, 10); } }
|
This 賦予到變數上
在寫物件內的傳統函式時,為了確保 this 能夠正確取得物件裡的變數,會先將它賦予在另一個變數上。
1 2 3 4 5 6 7 8 9 10 11 12
| var name = '全域阿婆' var auntie = { name: '漂亮阿姨', callName: function () { var vm = this; console.log('1', vm.name); // 漂亮阿姨 setTimeout(function () { console.log('2', vm.name); // 漂亮阿姨 }, 10); }
auntie.callName();
|
箭頭函式因環境取 this,可以不用重新指向。
1 2 3 4 5 6 7 8 9
| var auntie = { name: '漂亮阿姨', callName () { setTimeout(() => { console.log(this); // auntie 物件 }, 10); } } auntie.callName();
|
References
https://wcc723.github.io/javascript/2017/12/21/javascript-es6-arrow-function/