之前寫過“箭頭函數(shù):我只是this的搬運工”,這次更好的總結(jié)下。
箭頭函數(shù)與傳統(tǒng)JavaScript的不同之處,主要集中在一下幾點:
1. 沒有this
,super
,arguments
和new.target
綁定。
箭頭函數(shù)的中的this
,super
,arguments
及new.target
這些值由外圍最近一層非箭頭函數(shù)決定。
這句話的意思是,箭頭函數(shù)內(nèi)的能訪問到的這些值,其實都是來自于外圍的最近一層非箭頭函數(shù)內(nèi)的值。
舉個例子:
let person = {
name :'noshower',
getName(){
let self = this;
let fn = () => console.log(this === self);
fn();
}
}
person.getName();
//result : true
上面這個例子中,箭頭函數(shù)內(nèi)的this與外圍的非箭頭函數(shù)中的this值相等。
2. 不能通過new
關(guān)鍵字調(diào)用
箭頭函數(shù)沒有[[Construct]]
方法,所以不能被用作構(gòu)造函數(shù),如果通過new
關(guān)鍵字調(diào)用箭頭函數(shù),程序會拋出錯誤。
let F = () => {}
new F();
//result: TypeError: F is not a constructor
3.沒有原型
由于不可以通過new
關(guān)鍵字調(diào)用箭頭函數(shù),因而沒有構(gòu)建原型的需求,所以箭頭函數(shù)不存在prototype
這個屬性。
4. 不可以改變this
的綁定
函數(shù)內(nèi)部的this
值不可被改變,在函數(shù)的生命周期內(nèi)始終保持一致。
箭頭函數(shù):我連new都放棄,還要prototype干嘛!!!
5. 不支持arguments
對象。
箭頭函數(shù)沒有arguments綁定,所以你必須通過命名參數(shù)和不定參數(shù)這兩種形式訪問函數(shù)的參數(shù)。
在未來無論函數(shù)在哪個上下文中執(zhí)行,箭頭函數(shù)始終可以訪問外圍函數(shù)的arguments對象。
舉個例子:
let f = function returnArgument(){
return ()=> arguments;
}(1,2,3);
console.log(f());
// result: { '0': 1, '1': 2, '2': 3 }
上面這個例子,給箭頭函數(shù)的外圍非箭頭函數(shù)傳入3個參數(shù),然后返回箭頭函數(shù),再調(diào)用,結(jié)果表明,箭頭函數(shù)可以訪問外圍函數(shù)的arguments對象。
6.不支持重復(fù)的命名參數(shù)
無論在嚴(yán)格還是非嚴(yán)格模式下,箭頭函數(shù)都不支持重復(fù)的命名參數(shù):而在傳統(tǒng)函數(shù)的規(guī)定中,只有在嚴(yán)格模式下才不能有重復(fù)的命名參數(shù)。