javascript中的箭头函数是什么_与传统函数有何不同

箭头函数无this绑定、不可new调用、无arguments对象、不支持yield;传统函数具备这些特性,适用于需动态this、构造实例、参数反射或生成器的场景。

箭头函数没有自己的 this 绑定

这是最常踩坑的地方:箭头函数不创建自己的 this,而是沿用外层作用域的 this 值。传统函数(function 声明或表达式)在每次调用时会根据调用方式动态绑定 this

典型问题场景:

  • 对象方法中使用箭头函数,this 指向不是该对象,而是定义时的外层上下文(比如全局或模块顶层)
  • 事件回调里用箭头函数,本想访问触发元素(event.currentTarget),却误以为 this 就是它
  • Vue/React 类组件生命周期中,用箭头函数写方法,this 可能指向错误,导致无法访问 stateprops
const obj = {
  value: 42,
  regular() {
    return this.value; // ✅ 42
  },
  arrow: () => {
    return this.value; // ❌ undefined(this 是全局或 module.exports)
  }
};

箭头函数不能用作构造函数

调用 new 箭头函数会直接抛出 TypeError: xxx is not a constructor。传统函数有 [[Construct]] 内部方法,而箭头函数没有。

这意味着:

  • 不能用 new 实例化箭头函数
  • 没有 prototype 属性(arrowFn.prototype === undefined
  • 无法通过箭头函数实现“类式继承”或模拟构造行为
const Regular = function() { this.x = 1; };
const Arrow = () => { this.x = 1; };

new Regular(); // ✅ new Arrow(); // ❌ TypeError

箭头函数没有 arguments 对象

在传统函数内部,arguments 是一个类数组对象,包含所有传入参数。箭头函数不绑定 arguments,访问它会报 ReferenceError 或取到外层函数的 arguments

替代方案统一用剩余参数(...args)——它在两种函数中都可用,且更可靠:

  • 避免依赖 arguments.callee(已废弃)
  • 剩余参数是真数组,可直接用 .map().reduce()
  • ES6+ 环境下,剩余参数是标准做法,无兼容性问题
function traditional() {
  console.log(arguments[0]); // ✅ "hello"
}

const arrow = () => { console.log(arguments[0]); // ❌ ReferenceError };

const modern = (...args) => { console.log(args[0]); // ✅ "hello" };

箭头函数没有 yield,不能用作 Generator

箭头函数语法上就不支持 function* 形式,也无法在内部使用 yield 关键字。如果需要惰性求值、分步执行或暂停恢复逻辑,必须用传统 function*

常见误用:

  • 试图写 const gen = () => yield 1; → 语法错误
  • 把异步迭代逻辑(如 for await...of 配合 async function*)强行塞进箭头函数 → 不可行
function* generator() {
  yield 1;
  yield 2;
} // ✅

const bad = *() => { yield 1; }; // ❌ SyntaxError const alsoBad = () => { yield 1; }; // ❌ SyntaxError

箭头函数简洁,但它的“轻量”来自对运行时特性的主动放弃。真正要控制 this、实例化、参数反射或生成器行为时,传统函数不是过时,而是不可替代。