ES6-箭頭函式 (Arrow functions)

箭頭函式 () => {}

簡短的語法

一般使用箭頭函式與 function 的用法大致一致,可以傳入參數、也有大括號包起來,
除此之外箭頭函式也有更簡短的寫法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 正常寫法
var callSomeone = (someone) => {
return someone + '上工了'
}
console.log(callSomeone('伙計'))

// 縮寫,單一行陳述不需要 {}
var callSomeone = (someone) => someone + '上工了'
console.log(callSomeone('伙計'))

// 只有一個參數可以不加括號
var callSomeone = someone => someone + '上工了'
console.log(callSomeone('伙計'))

// 沒有參數時,一定要有括號
var callSomeone = () => '伙計' + '上工了'
console.log(callSomeone('伙計'))

注意
不過這個上述有個小地方也要注意一下,在大括號內的 {} 是需要自行加入 return
如果沒有傳入值則會出現 undefined

1
2
var callSomeone = (someone) => { someone + '上工了' }
console.log(callSomeone('伙計')) // undefined

綁定的 this 不同

口訣:

箭頭函式裡面的this 等於 外面的this

白話文:

箭頭函式裡的this 主要是依據 外層函式(function)裡的this 是什麼就跟著是什麼。

規則

1
2
3
4
5
6
function x(){
this <= 外層函式的this,規則參考「一般函式的this
const a = () => {
this <= 依據外層函式的this
}
}

範例

callName 是使用 一般函式
callName2 是使用 箭頭函式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var name = '全域阿婆'
var auntie = {
name: '漂亮阿姨',
callName: function () {
// 注意,這裡是 function,以此為基準產生一個作用域
console.log('1', this.name); // 1 漂亮阿姨(外層函式)
setTimeout(() => {
console.log('2', this.name); // 2 漂亮阿姨(依據外層函式的this)
console.log('3', this); // 3 auntie 這個物件(依據外層函式的this)
}, 10);
},
callName2: () => {
// 注意,如果使用箭頭函式,this 依然指向 window
console.log('4', this.name); // 4 全域阿婆(依據外層函式的this)
setTimeout(() => {
console.log('5', this.name); // 5 全域阿婆(依據外層函式的this)
console.log('6', this); // 6 window 物件(依據外層函式的this)
}, 10);
}
}

auntie.callName();
auntie.callName2();
補充:
因為 callName24 使用箭頭函式,所以 依據外層函式的this 的規則,就指向最外層window。

沒有 arguments 參數

注意:箭頭函數裡沒有argument物件,可使用 其餘參數(Rest Operator) 替代

1
2
const other = (...others) => others;
console.log(other(10, 20, 30, 40, 50)) // [10, 20, 30, 40, 50]

apply, call, bind 無效

this 在 Arrow function 中是被綁定的,所以套用 apply, call, bind 的方法時是無法修改 this


不能用在建構式

由於 this 的是在物件下建立,所以箭頭函式不能像 function 一樣作為建構式的函式,
如果嘗試使用此方法則會出現錯誤 (… is not a constructor)。


參考來源