4 回答

TA貢獻1797條經驗 獲得超4個贊
const trim = function( str ) {
return trim.replace( /^\s+|\s+$/g, '' );
};
使用箭頭函數:
const trim = str => trim.replace( /^\s+|\s+$/g, '' );
2. 在函數內部不需要自己的 this 指針的時候,非常方便,因為箭頭函數作用域內沒有 this
例如下面不使用箭頭函數的代碼, 要通過將 this 賦值給 me,調用 me 來調用 Obj:
const Obj = {
text : 'ABC',
replace : function( arr ) {
var me = this;
arr.forEach( function( item ) {
return me.text;
} );
}
};
使用箭頭函數:
const Obj = {
text : 'ABC',
replace : function( arr ) {
arr.forEach( item => this.text );
}
};
3. 還有一點是 箭頭函數沒有 arguments 變量,在某些時候也可以帶來方便,和上面差不多。
添加回答
舉報