为什么不应该使用箭头函数?

2025-06-08

为什么不应该使用箭头函数?

谁会不喜欢箭头函数的简洁呢?作为 ECMAScript 6 的一部分,箭头函数迅速走红。这种声明函数的新语法节省了我们的时间,并在许多情况下提高了代码清晰度,消除了声明 JS 函数时通常会带来的各种令人分心且不必要的繁琐步骤😫。在本文中,我们将详细讨论何时应该使用箭头函数,何时不应该使用箭头函数,所以请耐心阅读到最后,以免造成混淆。

常规函数声明

function holidays(){ 
return "Merry Christmas and a happy new year 😀!"
}
Enter fullscreen mode Exit fullscreen mode
const result = list.map(function(item) { return item; })
Enter fullscreen mode Exit fullscreen mode

使用 Es6 函数

const holidays = () => "Merry Christmas and a happy new year 😀!"
Enter fullscreen mode Exit fullscreen mode
const result = list.map((item) => item)
Enter fullscreen mode Exit fullscreen mode

是不是很棒?无论如何,我们都必须谨慎,因为它们之间的区别不仅仅是语法上的,所以我们不能在所有情况下都使用它。

那么什么时候不建议使用箭头函数

1. 对象方法

const post= {
likes: 0,
like: () => {
this.likes++;
}
}
Enter fullscreen mode Exit fullscreen mode

在上面的例子中,我们本能地认为每次调用post.like()该属性时post.likes它都会加一,最初从 0 到 1。
不幸的是,事实并非如此,点赞的价值将遗憾地保持不变,这篇文章永远不会流行。

调用方法 like() 只会尝试增加全局窗口对象上的属性 likes。

但是,如果我们使用传统的语法:

const post = {
likes: 0,
like: function() {
this.likes++;
}
}
Enter fullscreen mode Exit fullscreen mode

2. 对象原型

与上面的例子类似,对象原型将把它评估为全局窗口对象,如下例所示:

class Post {
constructor(title) {
this.title = title;
this.shared = false;
}
};

Post.prototype.share = () => {
return this.shared = true;
};
Enter fullscreen mode Exit fullscreen mode

类似地,在上一种情况下,由于作用域被限制在 window 对象中,方法 share() 也无法工作。解决方案看起来也很熟悉:

Post.prototype.share2 = function() { return this.shared = true; };
Enter fullscreen mode Exit fullscreen mode

除了上面我们看到的之外,这里还列出了箭头函数的一些限制:

  • 没有与 this 或 super 的绑定
  • 不应将其用作事件处理程序、对象的方法、类的方法或原型方法,或者当您有一个使用参数对象的函数时。
  • 不适用于 call、apply 和 bind 方法,这些方法通常依赖于建立范围
  • 不能用作构造函数
  • 不能在其主体内使用 yield

摘自 MDN

待续...

感谢您抽出时间阅读这篇文章,希望您喜欢。请在评论区告诉我您的想法,也别忘了在TwitterInstagramLinkedin上联系我。再次祝您圣诞快乐,2021 年新年快乐🌲。

鏂囩珷鏉ユ簮锛�https://dev.to/blessinghirwa/why-you-shouldn-t-use-arrow-functions-35mc
PREV
自定义省略的 Git Bash shell 行
NEXT
在 Svelte 安装中使用 API 我们正在做什么 概述