ES6:Arrow Functions
基本語法
(引數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: ƒ}
- 通過 call 或 apply 呼叫
由於 箭頭函式沒有自己的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