箭头函数无this、不能作构造函数、无arguments和yield,仅适用于简化回调。它继承外层this,不可用call/apply/bind修改,无prototype,不支持new,参数需用...args,返回对象须加括号。
this,它继承外层作用域的 this
这是最常踩坑的一点。传统函数(function)每次调用都会绑定自己的 this,取决于调用方式(如 obj.method() 中 this 指向 obj);而箭头函数不绑定 this,它直接沿用定义时所在词法作用域的 值。
this
this 指向意外(比如指向全局或 undefined).call()、.apply()、.bind() 改变箭头函数的 this
const obj = {
name: 'Alice',
regular() {
console.log(this.name); // 'Alice'
},
arrow: () => {
console.log(this.name); // undefined(非严格模式下可能是 globalThis)
}
};prototype
你不能对箭头函数使用 new 关键字,它没有 [[Construct]] 内部方法,也不会创建实例。同时,它没有 prototype 属性,因此不适合用来定义需要原型链继承的类行为。
new (() => {}) 会抛出 TypeError: xxx is not a constructor
function 或 class
arguments 对象,也不支持 yield
箭头函数内部访问 arguments 会报 ReferenceError,它只能靠显式参数或剩余参数(...args)获取入参;同时它不是生成器函数,不能用 yield,也不能用 async + yield 组合(但可以用 async 箭头函数)。
arguments:统一用 ...args 参数展开function*
async () => {} 是合法的,但 async () => { yield 1; } 语法错误const sum = (...nums) => nums.reduce((a, b) => a + b, 0); // 不要这样: // const bad = () => Array.from(arguments).reduce(...); // ReferenceError
return
单参数 + 单表达式可省略括号和 return,看起来干净,但一旦加了逻辑块(比如 if 或变量声明),就必须显式写 {} 和 return,否则返回 undefined。
x => x * 2 返回数值;x => { x * 2 } 返回 undefined(没写 return)() => ({ a: 1 }),否则会被解析为代码块arr.map(x => y => x + y))易读性下降,调试时堆栈也更扁平,不利于定位箭头函数不是万能替代品,它的设计初衷是简化回调和避免 this 绑定问题,而不是取代所有函数场景。什么时候该用、什么时候必须避开,关键看是否依赖 this、构造能力或参数动态性——这些地方一错就难调试。