在 JavaScript 中,函数是非常重要的概念。它们是一种可复用的代码块,可以执行特定的任务。在 ES6
中引入了箭头函数,它们看起来与传统的函数不同,但实际上有很多相似之处。在本文中,我们将介绍箭头函数和普通函数之间的五个主要区别。
区别一:this 的指向
在传统函数中, this 的值是在运行时确定的,取决于它如何被调用。这会导致 this 的值在不同的情况下出现意外的变化。比如:
const person = {
name: 'Alice',
sayName() {
console.log(this.name);
}
};
person.sayName(); // 输出 "Alice"
const sayName = person.sayName;
sayName(); // 报错,因为此时 this 指向 undefined
在上面的例子中,当把 sayName 分配给一个变量时,调用该函数将导致错误,因为 this 的值为 undefined ,而不是person 对象。
相比之下,箭头函数没有自己的 this 。它们采用定义它们的作用域中的 this 值。这意味着,无论如何调用箭头函数, this
始终指向相同的对象。
const person = {
name: 'Alice',
sayName: () => {
console.log(this.name);
}
};
person.sayName(); // 输出 undefined
const sayName = person.sayName;
sayName(); // 输出 undefined
在上面的例子中,箭头函数的 this 始终指向全局对象,因为它是在定义时捕获的。这通常不是我们想要的。