极简三分钟ES6 - 箭头函数

209 阅读2分钟

精简的函数快递员

想象箭头函数是一位高效的快递员,用最短路径(=>)传递数据

// 传统函数写法
function add(a, b) {
  return a + b;
}

// 箭头函数写法(直达路线)
const add = (a, b) => a + b;  
console.log(add(1,  2)); // 3(快递直达)

精简规则

单参数可省括号

const sayHi = name => `你好, ${name}!`;  
sayHi("小明"); // "你好, 小明!"

单行代码自动返回(无{}时)

const double = num => num * 2; // 直接返回结果

返回对象需加括号(避免与{}冲突)

const getUser = id => ({ id: id, name: "匿名" });

永不迷路的 this

箭头函数最强大的特性——继承外层 this 值,解决传统函数的 this 混乱问题

// 传统函数:this 随调用者变化
const obj1 = {
  name: "对象1",
  print: function() {
    setTimeout(function() {
      console.log(this.name);  // 输出 undefined(this指向window)
    }, 100);
  }
};

// 箭头函数:继承定义时的 this
const obj2 = {
  name: "对象2",
  print: function() {
    setTimeout(() => {
      console.log(this.name);  // 输出 "对象2"(继承print的this)
    }, 100);
  }
};

箭头函数就像带着GPS的快递员,永远记得出发地(定义时的作用域),不因中转站(调用位置)改变路线

一般常见的使用场景

简化回调函数

// 传统写法
[1, 2, 3].map(function(x) { return x * x; });

// 箭头函数版
[1, 2, 3].map(x => x * x); // [1, 4, 9]

操作数组方法

const sum = [1, 2, 3].reduce((total, num) => total + num, 0); // 6

固定 this 的场景(如事件监听)

button.addEventListener("click",  () => {
  console.log(this);  // 始终指向定义时的上下文
});

箭头函数 vs 普通函数

特性箭头函数普通函数
this 指向继承定义时的外层作用域由调用者决定
构造函数❌ 不可用✅ 可用
arguments 对象❌ 不可用✅ 可用
简洁性⭐⭐⭐⭐ 极高⭐⭐ 较低

牢记

“箭头函数像快递:路线短(语法简),认准出发地(this稳),不接大件货(无构造)。”