我个人觉得,非常好用,主要有一下几点吧:
提高开发效率,减少体力耀东
使用剪头函数不需要敲完整的 function 关键字, 同时如果只有行 return 语句的函数,还可以进一步简写:
例如 要定义一个 trim 函数,不使用箭头函数:
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;
} );