语法
- 单行箭头函数:
// 单参数
const fn = foo => `${foo} world`
// 多参数
const fn = (foo,bar) => foo+bar
- 多行箭头函数:
foo => {
return '${foo} world'
}
(foo,bar) => {
return foo+bar;
}
- 无参数箭头函数
const greet = () => 'Hello World'
书写
- 参数列表的右括弧,箭头在一行
const fn = (x,y) => {
return x*y
}
- 单行箭头函数返回对象,用圆括号包裹
const ids = [1,2,3];
const users = ids.map(id => ({id:id});
// [{id:1},{id:2},{id:3}]
箭头函数与传统函数的区别
- 箭头函数作为匿名函数不能作为构造函数
const B = ()=> ({wechar:"前端"})
let b = new B() // 报错
- 箭头函数不绑定arguments,可以使用剩余参数rest解决
function A(a){
console.log(arguments);
}
var B = (b)=> {
console.log(arguments);
}
var C = (...c)=> {
console.log(c);l
};
A(1);
B(2);
C(3);
- 箭头函数this指向具有穿透性,会捕获其所在的上下文的this值
- 箭头函数无原型属性
var a = ()=> {
return 'okok';
};
console.log(a.property);
- 箭头函数不能当作Generator函数,不能使用yield关键字
- 箭头函数对上下文的绑定是强制的,无法通过call或aplly改变