箭头函数无独立this,继承外层非箭头函数的this;不可作为构造函数,无prototype和arguments;单表达式可隐式返回,多参数需括号,无参需空括号。

箭头函数没有自己的 this,它继承外层作用域的 this
这是最常踩坑的地方。普通函数的 this 在调用时动态绑定(取决于怎么被调用),而箭头函数的 this 在定义时就固定了,永远指向外层最近的非箭头函数作用域的 this。
典型问题场景:
- 对象方法中写箭头函数:
const obj = { name: 'Alice', regular() { console.log(this.name); }, // 输出 'Alice' arrow: () => { console.log(this.name); } // 输出 undefined(this 指向全局或 module.exports) }; - 事件回调里:
button.addEventListener('click', () => { console.log(this); // 不是 button,而是外层函数的 this });应该用普通函数或显式绑定
箭头函数不能用作构造函数,也没有 prototype 和 arguments
你无法用 new 调用箭头函数,它没有 prototype 属性,也不能通过 arguments 访问实参(得改用 rest 参数 ...args)。
-
const F = () => {}; new F();→ 报错:TypeError: F is not a constructor -
const fn = () => { console.log(arguments); };→ 报错:ReferenceError: arguments is not defined,必须写成(...args) => console.log(args) - 想检测是否被
new调用?普通函数能靠new.target,箭头函数里new.target始终为undefined
简写语法省略 return 和花括号,但只适用于单表达式
当箭头函数体是单个表达式且没花括号时,会隐式返回结果;一旦加了花括号,就必须显式写 return,否则返回 undefined。
立即学习“Java免费学习笔记(深入)”;
-
x => x * 2等价于x => { return x * 2; } -
x => { x * 2 }❌ 不会返回值,等价于x => { x * 2; return undefined; } - 多参数必须加小括号:
(a, b) => a + b,单参数可省:x => x + 1,无参数必须写:() => 42
箭头函数不适用于需要动态 this、arguments 或构造能力的场景
它不是普通函数的“升级版”,而是语义不同的工具。选错会导致难以调试的行为差异。
- Vue / React 的生命周期方法、事件处理器、定时器回调中,若需访问组件实例的
this,别直接写箭头函数 - 需要
arguments做参数转发?用普通函数,或改用 rest 参数(更现代) - 要写类的实例方法、需要被
bind/call/apply控制this?用普通函数 - Node.js 中
module.exports或exports赋值时,别用箭头函数导出方法,否则this会丢失模块上下文
箭头函数的简洁性容易让人忽略它的绑定刚性——它不“适应”调用方式,只“记住”定义位置。真要替换普通函数前,先确认这三点:是否依赖 this 动态性、是否需作为构造器、是否在需要 arguments 的老代码里运行。











