使用语法
箭头函数有四种使用语法
单一参数的单行箭头函数
const fn= foo =>`${foo} world`;
这是箭头函数最简洁的形式,常用于用作简单的处理函数,如过滤。如下段代码所示:
let array=['a','bc','def','ghij'];
array=array.filter(item=>item.length>=2);
console.log(array); // ["bc", "def", "ghij"]
多参数的单行箭头函数
const fn=(foo,bar) => foo+bar
在实际开发中,函数的参数不会只有一个,在箭头函数中,多参数的语法跟普通函数一样,用括号包裹参数项。我们经常处理函数,如排序
let array=['a','bc','def','ghij'];
array=array.sort((a,b) => a.length < b.length);
多行箭头函数
单一参数,如下段代码所示
foo => {
return `${foo} world`;}
多个参数
(foo,bar) => {
return foo+bar;}
无参数箭头函数
如果一个箭头函数无参数传入,则需要用一对空的括号来表示空的参数列表。
const greet = () => 'Hello World'
书写箭头的函数过程中,我们应该注意以下几点
1、使用单行箭头函数时,应避免换行
错误的用法,如下段代码所示:
const fn=x
=> x*2 //SyntaxError
正确的写法,如下:
const fn= x => x*2 //ok
2、参数列别的右括弧、箭头应在一行
错误的用法,如下段代码所示:
const fn = (x,y) //SyntaxError
=> { return x*y;}
下段代码书写是正确的:
const fn = (x, y) => { return x * y }
3.单行箭头函数返回只能包含一条语句
错误的书写,如下段代码所示:
const fn1= x => x=x*2; return x+2; //SyntaxError
正确的书写,如下段代码所示:
const fn2= x => {
x=x*2; return x+2;} //ok
4、如果单行箭头返回一个对象,请用圆括号包裹
错误的书写,如下段代码所示,解析引擎会将其解析成一个多行箭头函数:
const ids=[1,2,3];
const users=ids.map(id=>{id:id});//[ undefined, undefined, undefined ]
正确的书写,如下段代码所示:
const ids=[1,2,3];
const users=ids.map(id=>({id:id}));//[ { id: 1 }, { id: 2 }, { id: 3 } ]
箭头函数里面的this
箭头函数里面的this指向父级执行上下文的this
1.箭头函数作为匿名函数,是不能作为构造函数的,不能使用new
const B = () => ({ wechat: "eehhe" });
let b = new B(); //TypeError: B is not a constructor
3.箭头函数没有原型属性
var a = () => {
return 'hhh';
}
function b() { return 'hhh'; } console.log(a.prototype);//undefined
4.箭头函数对上下文的绑定是强制的,无法通过call或aplly进行改变