← 返回目录

箭头函数

=> 写函数,比 function 更短;this 指向声明时所在的作用域。

1. 基本写法对比

以前 · function 现在 · 箭头函数
let sum = function (a, b) {
  return a + b;
};
console.log(sum(1, 2));
// 3
let sum = (a, b) => a + b;
console.log(sum(1, 2));
// 3

2. 各种参数写法

以前 现在
let say = function () {
  console.log("hello");
};
let hi = function (name) {
  return "hello " + name;
};
let say = () => console.log("hello");
let hi = name => "hello " + name;
// 一个参数可以省括号
// 一条语句可以省 {} 和 return

3. this 指向对比

以前 · function 现在 · 箭头函数
let obj = {
  name: "大喇叭",
  say: function () {
    setTimeout(function () {
      console.log(this.name);
      // undefined(this 指向 window)
    }, 100);
  }
};
let obj = {
  name: "大喇叭",
  say: function () {
    setTimeout(() => {
      console.log(this.name);
      // 大喇叭(this 指向 obj)
    }, 100);
  }
};
箭头函数:一个参数可省括号、一条语句可省花括号和 return;this 指向声明时所在作用域,且不能当构造函数(不能 new)。