箭头函数的用法及注意事项
基本使用
- 普通函数与箭头函数的区别:
// ES5的函数写法 let fun1 = function(me) {return me} // ES6的箭头函数写法 let fun2 = (me) => {return me} console.log(fun1('hello')); console.log(fun2('hello'));
简写:
-
如果函数的参数有且仅有一个时,可以省略参数的括号。
-
如果函数的方法体是单条语句时,可省略 return 关键字和花括号,但是要省略,则必须return 关键字和花括号都要省略,只省略一个则出现错误。
let fun1 = (me) => {return me} let fun2 = me => {return me} let fun3 = me => me console.log(fun1('hello')); console.log(fun2('hello')); console.log(fun3(123));
注意事项
-
箭头函数没有自己的 this、arguments、super 或 new.target,并且它不能用作构造函数,因此不能使用new命令。
-
箭头函数的 this:
箭头函数没有自己的 this,因此它只会从外层的作用域中找 this,并继承外层作用域的 this。function Fun() { console.log(this); // this指向该Fun对象 let fun1 = () => { console.log(this); // this指向外层作用域的this,即Fun对象 } // 调用箭头函数 fun1() } let fun2 = () => { console.log(this); // this指向外层作用域的this,即Windows对象 } // 创建对象 new Fun(); // 调用箭头函数 fun2()
-
箭头函数中大括号被解释为代码块,所以当箭头函数返回的是一个对象时,必须在对象外面加上括号,否则会报错。
let per = age => ({ age: age }); console.log(per(18));
-
由于箭头函数的加入使得this从动态变成静态,因此在使用到this时,慎用箭头函数避免不必要的Bug
参考:箭头函数