箭头函数无独立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 或构造能力的场景它不是普通函数的“升级版”,而是语义不同的工具。选错会导致难以调试的行为差异。
this,别直接写箭头函数arguments 做参数转发?用普通函数,或改用 rest 参数(更现代)bind/call/apply 控制 this?用普通函数module.exports 或 exports 赋值时,别用箭头函数导出方法,否则 this 会丢失模块上下文箭头函数的简洁性容易让人忽略它的绑定刚性——它不“适应”调用方式,只“记住”定义位置。真要替换普通函数前,先确认这三点:是否依赖 this 动态性、是否需作为构造器、是否在需要 arguments 的老代码里运行。