如何定义const函数javascript(语法糖)?

how to define const function javascript (syntactic sugar)?

我希望能够创建如下函数:

const function doSomething(){...}

然而看起来实现它的唯一方法是:

const doSomething=function(){...}

我错了吗?或者它实际上有语法糖吗?

const 在 JavaScript 中做的唯一一件事是防止重新分配变量。不要与防止值突变相混淆。

const 需要标识符、赋值运算符和右侧。将 const 与函数组合的唯一方法是使用函数表达式(您的第二个示例)。

const doSomething = function() {
  // do stuff
};
// will either throw an error or the value of doSomething simply won't change
doSomething = somethingElse;

许多人喜欢确保他们的函数被命名,以便名称出现在调用堆栈中,因此更喜欢使用函数声明(你的第一个例子)。但是,可以命名函数表达式。

const doSomething = function doSomething() {
  // name will appear as doSomething in the call stack
};