ES6 箭头函数和普通函数有什么区别?

2024-08-03 17:09:05 113
ES6 箭头函数(Arrow Functions)和普通函数(Regular Functions)在 JavaScript 中有几个关键的区别,这些区别主要体现在语法、this 绑定、arguments 对象以及用法上。

1. 语法

箭头函数的语法更简洁,不需要 function 关键字,并且如果只有一个参数时可以省略括号。如果函数体只有一个表达式,还可以省略大括号和 return 关键字。

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

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

// 无参数箭头函数
const greet = () => 'Hello';

// 单参数箭头函数
const square = x => x * x;

2. this 绑定

箭头函数不会创建自己的 this,它会捕获其所在上下文的 this 值,即所谓的“词法绑定” (lexical binding)。而普通函数会根据调用方式动态绑定 this

// 普通函数
function Person() {
  this.age = 0;
  setInterval(function growUp() {
    this.age++; // this 指向全局对象或 undefined(严格模式下)
  }, 1000);
}

// 使用箭头函数
function Person() {
  this.age = 0;
  setInterval(() => {
    this.age++; // this 指向 Person 实例
  }, 1000);
}

const p = new Person();

3. arguments 对象

箭头函数没有 arguments 对象。如果需要使用 arguments,可以使用 rest 参数 ...args 来代替。

// 普通函数
function sum() {
  let total = 0;
  for (let i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

// 箭头函数
const sum = (...args) => {
  return args.reduce((total, arg) => total + arg, 0);
};

4. 不能用作构造函数

箭头函数不能用作构造函数,不能使用 new 关键字实例化对象。

function Person(name) {
  this.name = name;
}

const john = new Person('John'); // 正常

const PersonArrow = (name) => {
  this.name = name;
};

const jane = new PersonArrow('Jane'); // TypeError: PersonArrow is not a constructor

5. 不能使用 yield 关键字

箭头函数不能用作生成器函数,不能使用 yield 关键字。

// 普通生成器函数
function* generatorFunction() {
  yield 1;
  yield 2;
  yield 3;
}

// 箭头函数不能用作生成器
const generatorFunction = () => {
  yield 1; // SyntaxError: Unexpected strict mode reserved word
};

6. 使用场景

  • 箭头函数:适合短小的、无 this 绑定需求的函数,如数组方法中的回调函数(如 mapfilterreduce)和事件处理函数。
  • 普通函数:适合需要动态 this 绑定、arguments 对象或构造函数的场景。

代码示例

下面的例子展示了箭头函数和普通函数在 this 绑定上的区别:

const obj = {
  value: 42,
  regularFunction: function() {
    console.log(this.value); // this 指向 obj,输出 42
  },
  arrowFunction: () => {
    console.log(this.value); // this 指向全局对象,输出 undefined
  }
};

obj.regularFunction();
obj.arrowFunction();

总结

箭头函数和普通函数在语法、this 绑定、arguments 对象、构造函数和生成器函数等方面有显著区别。理解这些区别有助于在合适的场景中选择合适的函数类型,从而编写更简洁、高效的代码。