箭头函数和普通函数的区别

96 阅读2分钟

箭头函数和普通函数(也称为函数声明或函数表达式)在 JavaScript 中都是用来创建新的函数的,但它们之间有一些重要的区别:

  1. 语法:箭头函数的语法更简洁
// 普通函数
function add(a, b) {
  return a + b;
}

// 箭头函数
const add = (a, b) => a + b;
  1. this 绑定:箭头函数不会创建自己的 this,它会从自己的作用域链上一级继承 this。而普通函数会创建自己的 this,指向调用它的对象(如果以对象方法形式调用)或者全局对象(如果直接调用)。
// 普通函数
const obj1 = {
  value: 'abc',
  createFunction: function() {
    return function() {
      console.log(this.value);
    }
  }
};
obj1.createFunction()(); // undefined

// 箭头函数
const obj2 = {
  value: 'abc',
  createFunction: function() {
    return () => {
      console.log(this.value);
    }
  }
};
obj2.createFunction()(); // 'abc'
  1. arguments 对象:箭头函数不会创建自己的 arguments 对象。它会从自己的作用域链上一级继承 arguments。而普通函数会创建自己的 arguments 对象。
// 普通函数
function checkArguments() {
  console.log(arguments);
}
checkArguments(1, 2, 3); // Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]

// 箭头函数
const checkArguments = () => {
  console.log(arguments);
}
checkArguments(1, 2, 3); // ReferenceError: arguments is not defined
  1. 构造函数:箭头函数不能用作构造函数,不能使用 new 关键字,因为它没有自己的 this,也没有 constructor。而普通函数可以用作构造函数。
// 普通函数
// 普通函数
function Person(name) {
  this.name = name;
}
const person = new Person('John'); // Works fine

// 箭头函数
const Person = (name) => {
  this.name = name;
}
const person = new Person('John'); // TypeError: Person is not a constructor
  1. 原型:由于箭头函数不能用作构造函数,所以它也没有 prototype 属性。而普通函数由于可以作为构造函数,所以它有 prototype 属性。
// 普通函数
function normalFunc() {}
console.log(normalFunc.prototype); // {constructor: ƒ}

// 箭头函数
const arrowFunc = () => {}
console.log(arrowFunc.prototype); // undefined
  1. yield 关键字:箭头函数不能包含 yield 关键字,所以不能用作生成器函数。而普通函数可以包含 yield 关键字,可以用作生成器函数。

这些区别使得箭头函数和普通函数在不同的场景下各有优势。