文章列表

箭头函数 vs 普通函数

Champ2025.12.25 18:30访问量0 次阅读
箭头函数 vs 普通函数
箭头函数和普通函数有什么区别?

箭头函数(Arrow Function)是 ES6 引入的重要特性,与普通函数(传统函数)有以下主要区别:

1. 语法简洁性

// 普通函数
function add(a, b) {
  return a + b;
}

// 箭头函数
const add = (a, b) => a + b;  // 隐式返回

2. this 指向(最重要的区别)

普通函数

function Person() {
  this.age = 0;

  setInterval(function growUp() {
    // 这里的 this 指向全局对象(或undefined)
    this.age++;  // 错误!this.age 为 undefined
  }, 1000);
}

箭头函数

function Person() {
  this.age = 0;

  setInterval(() => {
    // 箭头函数没有自己的 this,继承外层作用域的 this
    this.age++;  // 正确!this 指向 Person 实例
  }, 1000);
}

关键区别

  • 普通函数:this 由调用方式决定(动态绑定)
  • 箭头函数:this 在定义时继承自外层作用域(词法绑定)

3. 构造函数能力

// 普通函数可以作为构造函数
function Person(name) {
  this.name = name;
}
const p = new Person('张三');  // 正确

// 箭头函数不能作为构造函数
const Person = (name) => {
  this.name = name;
};
const p = new Person('张三');  // 报错:Person is not a constructor

4. arguments 对象

// 普通函数有 arguments 对象
function sum() {
  console.log(arguments);  // [1, 2, 3]
}
sum(1, 2, 3);

// 箭头函数没有自己的 arguments 对象
const sum = () => {
  console.log(arguments);  // 报错或指向外层 arguments
};

// 替代方案:使用剩余参数
const sum = (...args) => {
  console.log(args);  // [1, 2, 3]
};

5. 原型属性(prototype)

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

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

6. yield 关键字

  • 普通函数:可以用作生成器函数(使用 yield
  • 箭头函数:不能用作生成器函数

7. 参数重名

// 普通函数允许
function foo(a, a) {  // 严格模式下会报错
  console.log(a);
}

// 箭头函数不允许
const foo = (a, a) => {  // 语法错误
  console.log(a);
};

8. 方法简写

const obj = {
  // 普通函数作为方法
  regularMethod: function() {
    // this 指向 obj
  },

  // ES6 方法简写
  shorthandMethod() {
    // this 指向 obj
  },

  // 箭头函数作为方法(不推荐)
  arrowMethod: () => {
    // this 不指向 obj,而是外层作用域
  }
};

使用建议

使用箭头函数:

  1. 回调函数(尤其是需要保持 this 一致时)
  2. 简短的单行函数
  3. 需要继承外层 this 的场景
  4. 函数式编程中的纯函数
// 适合的场景
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);

// 保持 this 一致
class Button {
  constructor() {
    this.clicked = false;
    this.element = document.createElement('button');

    // 使用箭头函数确保 this 指向 Button 实例
    this.element.addEventListener('click', () => {
      this.clicked = true;  // 正确访问实例属性
    });
  }
}

使用普通函数:

  1. 构造函数
  2. 对象方法(需要访问对象自身)
  3. 需要动态 this 的场景
  4. 生成器函数
  5. 需要使用 arguments 对象的场景
// 适合的场景
function MyClass() {
  // 构造函数
}

const obj = {
  name: '对象',
  greet() {
    // 作为对象方法
    console.log(`Hello from ${this.name}`);
  }
};

总结

箭头函数主要优势在于:

  1. 更简洁的语法
  2. 自动绑定外层 this,避免 this 指向问题
  3. 更函数式的编程风格

但在需要动态 this、构造函数或访问 arguments 等场景下,仍需使用普通函数。

历史留言 (0)
ICP备案号浙ICP备2026065730号-1公安备案号浙公网安备33019202003213号