1. 箭头函数

66 阅读1分钟

语法

  1. 单行箭头函数:
// 单参数
const fn = foo => `${foo} world` ;

// 多参数
const fn = (foo,bar) => foo+bar ; 
  1. 多行箭头函数:
// 单参
foo => {
    return '${foo} world'
}

// 多参
(foo,bar) => {
    return foo+bar;
}
  1. 无参数箭头函数
const greet = () => 'Hello World'

书写

  1. 参数列表的右括弧,箭头在一行
const fn = (x,y) => {
    return x*y
}
  1. 单行箭头函数返回对象,用圆括号包裹
const ids = [1,2,3];
const users = ids.map(id => ({id:id});
// [{id:1},{id:2},{id:3}]

箭头函数与传统函数的区别

  1. 箭头函数作为匿名函数不能作为构造函数
const B = ()=> ({wechar:"前端"});
let b = new B()    // 报错
  1. 箭头函数不绑定arguments,可以使用剩余参数rest解决
function A(a){
    console.log(arguments);
}
var B = (b)=> {
    console.log(arguments);
}
var C = (...c)=> {    // c为rest参数
    console.log(c);l
};
A(1);
B(2);
C(3);
  1. 箭头函数this指向具有穿透性,会捕获其所在的上下文的this值
  2. 箭头函数无原型属性
var a = ()=> {
    return 'okok';
};
console.log(a.property);    // undefine
  1. 箭头函数不能当作Generator函数,不能使用yield关键字
  2. 箭头函数对上下文的绑定是强制的,无法通过call或aplly改变