4 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊
提高開(kāi)發(fā)效率,減少體力耀東
使用剪頭函數(shù)不需要敲完整的 function 關(guān)鍵字, 同時(shí)如果只有行 return 語(yǔ)句的函數(shù),還可以進(jìn)一步簡(jiǎn)寫(xiě):
例如 要定義一個(gè) trim 函數(shù),不使用箭頭函數(shù):
const trim = function( str ) {
return trim.replace( /^\s+|\s+$/g, '' );
};
使用箭頭函數(shù):
const trim = str => trim.replace( /^\s+|\s+$/g, '' );
2. 在函數(shù)內(nèi)部不需要自己的 this 指針的時(shí)候,非常方便,因?yàn)榧^函數(shù)作用域內(nèi)沒(méi)有 this
例如下面不使用箭頭函數(shù)的代碼, 要通過(guò)將 this 賦值給 me,調(diào)用 me 來(lái)調(diào)用 Obj:
const Obj = {
text : 'ABC',
replace : function( arr ) {
var me = this;
arr.forEach( function( item ) {
return me.text;
} );
}
};
使用箭頭函數(shù):
const Obj = {
text : 'ABC',
replace : function( arr ) {
arr.forEach( item => this.text );
}
};
3. 還有一點(diǎn)是 箭頭函數(shù)沒(méi)有 arguments 變量,在某些時(shí)候也可以帶來(lái)方便,和上面差不多。
添加回答
舉報(bào)