箭头函数和普通函数有哪些区别?

核心区别

特性 普通函数 箭头函数
this 动态绑定,由调用方式决定 词法 this,继承外层作用域
arguments 有自己的 arguments 没有,用 ...args 代替
new 可作为构造函数 ❌ 不能用 new
prototype 有 ❌ 没有
super ❌ ✅ 可访问外层的 super
yield 可用作 generator ❌ 不能
严格模式 需声明 'use strict' 内部默认严格模式

this 的差异

const obj = {
  count: 0,
  // 普通函数:this → obj
  normalIncrement() {
    setInterval(function () {
      this.count++  // ❌ this → window
    }, 1000)
  },
  // 箭头函数:this → obj(继承外层)
  arrowIncrement() {
    setInterval(() => {
      this.count++  // ✅ this → obj
    }, 1000)
  }
}

不能使用箭头函数的场景

  1. 对象方法(需要动态 this)
  2. 原型方法
  3. 构造函数
  4. 事件监听器(需要 this 指向 DOM 元素)
  5. Vue 选项式 API 的 methods
// ❌ 不适合
const obj = {
  name: 'Tom',
  sayHi: () => console.log(this.name)  // this → window
}

// ✅ 适合
const obj = {
  name: 'Tom',
  sayHi() { console.log(this.name) }
}

同分类其他题目