箭头函数不是语法糖,它与function函数在this绑定、无法new调用、无arguments和yield、单表达式隐式返回等核心行为上存在本质差异,不可随意互换。

箭头函数不是语法糖,它和 function 关键字声明的函数在 this、arguments、new 调用等核心行为上存在本质差异,不能随意互换。
箭头函数没有自己的 this,始终继承外层作用域的 this
这是最常踩坑的一点。传统函数的 this 取决于调用方式(如 obj.fn() 中 this 指向 obj),而箭头函数根本不绑定 this,它只是沿作用域链向上找外层函数的 this 值。
常见错误现象:
- 对象方法写成箭头函数后,
this指向全局或undefined(严格模式) - 事件回调里用箭头函数,本想访问实例属性却报
Cannot read property 'xxx' of undefined
const obj = {
name: 'Alice',
regularFn: function() {
console.log(this.name); // 'Alice'
},
arrowFn: () => {
console.log(this.name); // undefined(浏览器中是 window.name,通常为空)
}
};箭头函数不能作为构造函数,也不能使用 new
它没有 [[Construct]] 内部方法,也没有 prototype 属性。一旦尝试 new 一个箭头函数,会直接抛出 TypeError: xxx is not a constructor。
立即学习“Java免费学习笔记(深入)”;
使用场景限制:
- 不能用于定义类或需要实例化的工具函数
- Vue 2 的
data选项若写成箭头函数,会导致this失效,进而data返回空对象 - React 类组件中,生命周期方法、
render等不能用箭头函数定义(否则无法被框架正确调用)
箭头函数没有 arguments,也不支持 yield
它无法通过 arguments 访问实参列表,也不能用作 Generator 函数。替代方案是使用剩余参数 ...args。
参数差异与兼容性影响:
-
function fn() { console.log(arguments[0]); }✅ 可用 -
const fn = () => { console.log(arguments[0]); }❌ 报ReferenceError: arguments is not defined -
const fn = (...args) => console.log(args[0]);✅ 推荐写法 -
const gen = () => { yield 1; }❌ 语法错误:箭头函数不能含yield
箭头函数体为单表达式时可省略 return 和花括号
这是唯一一个纯语法便利点,但要注意隐式返回的边界:
-
x => x * 2→ 隐式返回数值 -
x => { x * 2 }→ 没有return,实际返回undefined -
x => ({ id: x })→ 圆括号包裹对象字面量,避免被解析为代码块
容易忽略的是:一旦加了花括号,就必须显式写 return,否则返回值永远是 undefined —— 这在 map、filter 等高阶函数中极易导致逻辑静默失败。











