箭头函数使用

# 箭头函数使用

  1. 一行语句且无需返回值
let fn = () => void doesNotReturn();
  1. 可以与结构配合
const full = ({ first, last }) => first + ' ' + last;
  1. 配合扩展运算符
const numbers = (...nums) => nums;

numbers(1, 2, 3, 4, 5)
// [1,2,3,4,5]

# 箭头函数特点

  1. 没有自己的this上下文。this固定指向上层作用域的this。具有固化this指向的功能。

  2. 不可以作为构造函数,也就是不能使用new命令.

  3. 不可以使用arguments对象,用rest(扩展运算符)取代。

  4. 不可以使用yeild命令。

# this

function foo() {
  return () => {
    return () => {
      return () => {
        console.log('id:', this.id);
      };
    };
  };
}
// this都指向foo

箭头函数使用call/bind/apply无效。

# 不适用场景

  1. 不要用箭头函数定义对象的方法。

  2. 要使用动态this的场景,例如绑定事件监听的回调中使用this去访问绑定对象。