javascript箭头函数与传统函数有何不同?【教程】

箭头函数不是语法糖,它不绑定this、arguments,不可new调用,无prototype,仅固定词法作用域;适用回调和React事件处理器,禁用于对象方法、构造函数及需动态this的场景。

箭头函数不是传统函数的语法糖,它和 function 声明/表达式在 thisargumentsnew 调用等核心行为上存在不可忽略的语义差异。

箭头函数没有自己的 this,永远继承外层作用域

这是最常踩坑的一点。箭头函数不绑定 this,它直接沿用定义时所在词法作用域的 this 值,而不是调用时的上下文。

常见错误现象:在对象方法中用箭头函数,结果 this 指向全局或 undefined(严格模式):

const obj = {
  name: 'Alice',
  regularFn: function() { console.log(this.name); }, // 正确输出 'Alice'
  arrowFn: () => { console.log(this.name); }        // 输出 undefined(浏览器中可能是 window.name)
};

使用场景:

  • 回调中避免 this 丢失(如 setTimeoutmap、事件监听器)
  • React 函数组件内写事件处理器,无需在 constructor 绑定 this
  • 但绝不能用于需要动态 this 的对象方法或原型方法

箭头函数没有 arguments 对象,也不支持 new

箭头函数内部访问 arguments 会报 ReferenceError,因为它根本没这个绑定;同时它没有 [[Construct]] 内部方法,调用 new 会直接抛出 TypeError

示例:

const bad = () => { console.log(arguments); }; // ReferenceError: arguments is not defined
const alsoBad = () => {};
new alsoBad(); // TypeError: arrowBad is not a constructor

替代方案:

  • 用剩余参数 ...args 替代 arguments
  • 需要用 new 实例化的必须用 function 声明或类(class
  • 构造函数、工厂函数、需要 prototype 的场景一律避开箭头函数

return 隐式与单表达式体的限制

箭头函数在单个表达式且无大括号时自动返回值,但一旦加了 {},就必须显式写 return,否则返回 undefined

容易混淆的写法:

const add = (a, b) => a + b;           // ✅ 返回数值
const makeObj = (a, b) => ({ a, b });  // ✅ 返回对象(小括号包裹避免被解析为代码块)
const broken = (a, b) => { a, b };      // ❌ 返回 undefined({ a, b } 是代码块,不是对象字面量)

注意点:

  • 返回对象字面量必须用 (...) 包裹,否则 JS 解析器会把 { 当作函数体开始
  • 多语句逻辑必须用 {} + return,不存在“隐式返回多行”
  • 没有函数名,name 属性是空字符串((() => {}).name === ''

真正关键的区别不在写法简洁性,而在于「是否拥有独立执行上下文」——箭头函数刻意放弃了 thisargumentsnew.targetprototype,它只做一件事:固定词法作用域。用错场景比语法写错更难调试。