箭头函数没有自己的this,继承外层词法作用域的this;不能用作构造函数,无prototype、arguments、caller、callee、yield,也不支持new调用,适用于无需独立this和构造能力的场景。
this,它继承外层作用域的 this
这是最常踩坑的一点。普通函数的 this 在调用时动态绑定(取决于怎么调用),而箭头函数压根不绑定 this,它直接从定义时的词法作用域向上查找 this 值。
典型问题场景:给 DOM 元素绑定事件、在对象方法中使用定时器、Vue/React 组件里写回调。
const obj = {
name: 'Alice',
say: function() { console.log(this.name) }
}
obj.say() // 'Alice';但 setTimeout(obj.say, 100) 会输出 undefined(因为 this 指向全局)const obj = {
name: 'Alice',
say: () => { console.log(this.name) } // 这里的 this 是定义时外层的 this,不是 obj
}
// 即使调用 obj.say(),也几乎肯定不是你想要的结果prototype 和 arguments
它没有 [[Construct]] 内部方法,所以不能用 new 调用;同时没有 prototype 属性,也不能被原型链继承;也没有独立的 arguments 对象(得靠 rest 参数 ...args 替代)。
const Arrow = () => {}
new Arrow() // TypeError: Arrow is not a constructorarguments:function old(a, b) { console.log(arguments[0]) }
const arrow = (...args) => { console.log(args[0]) }arguments、caller、callee,也不支持 yield
这些是普通函数的特有属性或能力。箭头函数设计初衷就是“轻量级函数表达式”,不承担构造、动态参数捕获或协程职责。
arguments 不可用 → 必须用 rest 参数;caller/callee 在严格模式下本就禁用,但箭头函数彻底没这俩属性;yield 不能用 → 要写生成器必须用 funct
ion*,不能写 () => yield;name 属性(或为 ""),调试时堆栈里显示为 anonymous。一是「不需要自己的 this」,二是「不需要被 new 调用」。常见于:数组方法回调(map/filter/reduce)、事件监听器(当需要闭包访问外层变量时)、Promise 链中的 then 回调。
[1, 2, 3].map(x => x * 2)
button.addEventListener('click', () => this.handleClick()) // this 指向组件实例const utils = {
now() { return Date.now() },
delay: () => setTimeout(this.now, 100) // ❌ this.now 是 undefined,因为箭头函数的 this 不是 utils真正容易被忽略的是:箭头函数的简洁性会掩盖它对执行上下文的“无感”——它不关心你怎么调用它,只认自己出生的地方。写之前先问一句:这里需要自己的 this 吗?需要被 new 吗?需要动态参数吗?答案只要有一个“是”,就别用箭头函数。