【js篇】箭头函数与普通函数的区别详解

274 阅读3分钟

在 JavaScript 中,箭头函数(Arrow Function) 是 ES6 引入的一种新的函数写法。它不仅简化了函数的定义方式,还在作用域绑定、this 指向等方面带来了显著差异。


✅ 一、一句话总结

箭头函数比普通函数更简洁,没有自己的 thisargumentsprototype,也不可以作为构造函数使用;它的 this 是词法作用域继承来的,一旦确定就不会改变。


✅ 二、具体区别对比表

特性普通函数箭头函数
是否有 this 绑定✅ 有自己的 this❌ 没有,继承外层作用域的 this
是否可以作为构造函数✅ 可以❌ 不可以(不能用 new
是否有 arguments 对象✅ 有❌ 没有(可用 ...args 替代)
是否有 prototype 属性✅ 有❌ 没有
是否支持简写语法❌ 否✅ 是(参数和返回值可省略括号/大括号)
this 是否可变✅ 可变(运行时绑定)❌ 固定(词法作用域绑定)

✅ 三、详细解析

1️⃣ 更加简洁的语法

✅ 无参数:

const sayHello = () => console.log('Hello');

✅ 单个参数(可省略括号):

const square = x => x * x;

✅ 多个参数(必须加括号):

const add = (a, b) => a + b;

✅ 返回值单行表达式(可省略 {}return):

const double = x => x * 2;

✅ 执行副作用语句(使用 void 避免隐式返回):

const fn = () => void someFunction(); // 防止返回值污染

2️⃣ 没有自己的 this

这是箭头函数最核心的特点之一。

  • 普通函数中的 this 是动态的,根据调用方式不同而变化;
  • 箭头函数中的 this 是词法作用域继承的,即定义时就决定了,不会随调用方式改变;

示例说明:

var id = 'GLOBAL';

var obj = {
  id: 'OBJ',
  a: function() {
    console.log(this.id);
  },
  b: () => {
    console.log(this.id);
  }
};

obj.a();    // 'OBJ' (this 指向 obj)
obj.b();    // 'GLOBAL'(this 指向外层 window/global)

new obj.a(); // this 指向新对象,输出 undefined(因为新对象没有 id)
new obj.b(); // 报错:Uncaught TypeError: obj.b is not a constructor

📌 结论:

  • a() 是普通函数,其 this 根据调用者动态绑定;
  • b() 是箭头函数,this 指向定义时的外层上下文(全局作用域);
  • 箭头函数不能作为构造函数,所以不能用 new 调用;

3️⃣ 没有 arguments 对象

箭头函数内部无法使用 arguments,但可以通过 ...args 获取所有参数。

示例:

const logArgs = (...args) => {
  console.log(args);
};

logArgs(1, 2, 3); // [1, 2, 3]

4️⃣ 没有 prototype 属性

function Foo() {}
console.log(Foo.prototype); // {constructor: ...}

const Bar = () => {};
console.log(Bar.prototype); // undefined

📌 因为箭头函数不能作为构造函数,自然也没有原型属性。


5️⃣ 不能作为构造函数(不可 new

const Person = () => {};
const p = new Person(); // TypeError: Person is not a constructor

✅ 四、应用场景建议

场景推荐使用原因
方法或回调中需要绑定 this✅ 箭头函数自动继承外层 this,避免 .bind(this) 或保存 that = this
构造函数、类方法❌ 箭头函数 ✅ 普通函数箭头函数不能作为构造函数,也无法绑定 this 到实例
需要 arguments 的场景❌ 箭头函数 ✅ 普通函数(或使用 ...args箭头函数不支持 arguments
需要 prototype 的场景❌ 箭头函数 ✅ 普通函数箭头函数没有 prototype

✅ 五、一句话总结

箭头函数是现代 JavaScript 中非常实用的语法糖,适合用于不需要自身 thisarguments 或构造功能的场景。但在需要构造函数、动态 this 或访问 arguments 的情况下,应优先使用普通函数。


💡 进阶建议

  • 在 Vue / React 中,组件方法推荐使用箭头函数自动绑定 this
  • 使用 TypeScript 可以帮助你更好地理解函数类型和 this 的指向;
  • 使用 ESLint 规则防止误将箭头函数当作构造函数使用;
  • 结合 class 使用箭头函数字段,可以自动绑定 this(如 class MyClass { myMethod = () => {} });