箭头函数是普通函数的语法糖加行为约束,无this/arguments/prototype,其this捕获定义时外层作用域值且不可变;需动态this、构造、arguments或原型操作时必须用普通函数。
箭头函数不是“另一种函数”,而是普通函数的语法糖 + 行为约束组合体——它省略了 function 关键字,但代价是放弃对 this、arguments、prototype 的控制权。
this 总不对?这是最常踩坑的地方:普通函数的 this 在运行时动态绑定(谁调用,this 就指向谁);而箭头函数根本没有自己的 this,它直接捕获定义时外层作用域的 this 值,且之后永不改变。
this 指向外层(通常是 window 或 undefined),不是对象本身this 不是触发事件的 DOM 元素,而是定义该箭头函数时的作用域call/apply/bind 强行改 this?无效 —— 箭头函数忽略所有显式绑定const obj = {
name: 'Alice',
regular() { console.log(this.name); }, // ✅ 输出 'Alice'
arrow: () => { console.log(this.name); } // ❌ 输出 undefined(this 指向全局)
};
obj.regular(); // 'Alice'
obj.arrow(); // undefined
当需要以下任一能力时,不能用箭头函数:
new MyFunc())→ 箭头函数会抛出 TypeError: MyFunc is not a constructor
arguments 对象 → 箭头函数里访问 arguments 会报 ReferenceError,得改用 rest 参数 ...args
MyFunc.prototype)→ 箭头函数没有 prototype 属性this 绑定 → 类方法应写成普通函数或使用属性初始化器 + 箭头函数(靠闭包捕获)// ❌ 报错:箭头函数不能 new
const Person = (name) => { this.name = name };
new Person('Bob'); // TypeError
// ✅ 普通函数可正常构造
function Person(name) { this.name = name }
const p = new Person('Bob');
核心原则:只用于「不需要控制 this、不需构造、不需 arguments」的轻量回调。
map、filter、reduce)→ 简洁且天然避免 this 丢失onClick={() => doSomething(id)})→ 避免重复绑定,也规避 this 问题const isValid = (x) => x > 0 && x )→ 语法干净,意图明确
// ✅ 推荐:filter 回调简洁安全
[1, 2, 3, 4].filter(x => x % 2 === 0); // [2, 4]
// ❌ 不推荐:在需要 this 指向对象自身时硬套箭头函数
const timer = {
delay: 1000,
start() {
setTimeout(() => {
console.log(this.delay); // ✅ 正确:this 捕获自 start(
)
}, this.delay);
}
};
真正容易被忽略的点是:箭头函数的「词法 this」看似省事,实则把上下文绑定时机从「调用时」提前到了「定义时」。一旦嵌套层级变深或模块拆分后作用域变化,this 的来源就变得隐晦难查——这时候宁可多写几个 function,也别靠猜。