箭头函数不是语法糖,它与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。
使用场景限制:
data 选项若写成箭头函数,会导致 this 失效,进而 data 返回空对象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 等高阶函数中极易导致逻辑
静默失败。