基本語法
(參數1, 參數2..., 參數n) => {函數聲明}
單一參數 => { 函數聲明 }
(參數1, 參數2...) => 單一表達式
() => { 函數聲明 }
與通常 function 的區別
- 箭頭函數中的 this 指向的是定義時的對象,而不是使用時的對象
// 事件綁定
document.body.addEventListener('click', () => {
console.log(this) // Window Object
})
document.body.addEventListener('click', function(){
console.log(this) // body object
})
// 對象中的方法
var a = {
name: 'a',
getname: () => {
console.log(this)
}
}
a.getname() // Window
var a = {
name: 'a',
getname: function(){
console.log(this)
}
}
a.getname() // {name: "a", getname: ƒ}
因爲 箭頭函數沒有本身的this指針,經過 call() 或 apply() 方法調用一個函數時,只能傳遞參數,他們的第一個參數會被忽略
let f = (val) => {
console.log(this);
console.log(val);
}
let obj = { count: 1};
f.call(obj, 'test')
輸出: Window
test
- 不能夠使用arguments對象,該對象在函數體內不存在。若是要用,能夠用 rest 參數代替
let fn = (a, b) => {
console.log(arguments) // 報錯
}
// rest參數替代
let fn = (...rest) => {
console.log(rest);
}
fn(1, 2); // [1,2]
- 不能用箭頭函數定義構造函數,箭頭函數不存在 prototype;所以也不能經過 new 關鍵字調用
let FN = () => {}
console.log(FN.prototype) // undefined
let fn = new FN(); // Uncaught TypeError: A is not a constructor
原文連接:https://arronf2e.github.io/post/es6-arrow-functionsgit