本文介绍了用 const 和箭头定义的 JavaScript 函数与常规函数有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 redux 代码中看到了几次:

I've seen this a few times with redux code:

const mapDispatchToProps = (dispatch) => {
  ...
}

function mapStateToProps(state) {
  ...
}

这样做是否有任何原因,这只是一种约定,一种复制粘贴代码的情况,还是这样做有什么好处?

Is there any reason why this is done, is it just a convention, a case of copy-paste code, or is there some benefit to doing it this way?

我已经读过箭头函数与常规函数会自动绑定 this,但这些函数似乎根本不存在于一个类中,所以也许这没有区别?

I've read that arrow functions vs regular functions automatically bind this, but it doesn't appear that these functions exist within a class at all, so maybe that makes no difference?

推荐答案

我认为这是一个品味问题;除了明显的差异(例如,函数表达式不会被提升)在您的情况下两者的工作方式几乎相同.

I think it's a matter of taste; aside from the obvious differences (ex. function expressions won't be hoisted) both work pretty much the same in your case.

参加防御性编程考虑到,如果您尝试重新定义常量,而重新声明函数(静默地)替换先前声明的函数,则前一种语法会导致解释器引发 SyntaxError.

Taking defensive-programming into account, the former syntax causes the interpreter to raise a SyntaxError if you try to redefine the constant whereas re-declaring a function (silently) replaces the previously declared one.

这篇关于用 const 和箭头定义的 JavaScript 函数与常规函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 02:50