语法错误:函数语句需要名称

当代码中存在需要名称的 函数语句 时,就会发生 JavaScript 异常 "函数语句需要名称"。

¥The JavaScript exception "function statement requires a name" occurs when there is a function statement in the code that requires a name.

信息

¥Message

SyntaxError: Function statements require a function name (V8-based)
SyntaxError: function statement requires a name (Firefox)
SyntaxError: Function statements must have a name. (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

代码中有一个 函数语句 需要一个名字。你需要检查函数是如何定义的,以及是否需要为其提供名称,或者相关函数是否需要是函数表达式、IIFE,或者函数代码是否正确放置在此上下文中 。

¥There is a function statement in the code that requires a name. You'll need to check how functions are defined and if you need to provide a name for it, or if the function in question needs to be a function expression, an IIFE, or if the function code is placed correctly in this context at all.

示例

¥Examples

语句与表达式

¥Statements vs. expressions

函数语句(或函数声明)需要一个名称。这是行不通的:

¥A function statement (or function declaration) requires a name. This won't work:

js
function () {
  return "Hello world";
}
// SyntaxError: function statement requires a name

你可以使用 函数表达式(作业)代替:

¥You can use a function expression (assignment) instead:

js
const greet = function () {
  return "Hello world";
};

如果你的函数旨在成为 IIFE(立即调用函数表达式,即定义后立即运行的函数),你将需要添加更多大括号:

¥If your function is intended to be an IIFE (Immediately Invoked Function Expression, which is a function that runs as soon as it is defined) you will need to add a few more braces:

js
(function () {
  // …
})();

标记函数

¥Labeled functions

标签 是与函数名称完全不同的特性。你不能使用标签作为函数名称。

¥Labels are an entirely different feature from function names. You can't use a label as a function name.

js
function Greeter() {
  german: function () {
    return "Moin";
  }
}
// SyntaxError: function statement requires a name

此外,带标签的函数声明本身也是一个已弃用的功能。请改用常规函数声明。

¥In addition, labeled function declarations themselves are a deprecated feature. Use regular function declarations instead.

js
function Greeter() {
  function german() {
    return "Moin";
  }
}

对象方法

¥Object methods

如果你打算创建对象的方法,则需要创建一个对象。下面的 function 关键字后面没有名称的语法是有效的。

¥If you intended to create a method of an object, you will need to create an object. The following syntax without a name after the function keyword is valid then.

js
const greeter = {
  german: function () {
    return "Moin";
  },
};

你也可以使用 方法语法

¥You can also use the method syntax.

js
const greeter = {
  german() {
    return "Moin";
  },
};

回调语法

¥Callback syntax

另外,使用回调时请检查语法。大括号和逗号很快就会变得混乱。

¥Also, check your syntax when using callbacks. Braces and commas can quickly get confusing.

js
promise.then(
  function () {
    console.log("success");
  });
  function () {
    console.log("error");
}
// SyntaxError: function statement requires a name

正确的是:

¥Correct would be:

js
promise.then(
  function () {
    console.log("success");
  },
  function () {
    console.log("error");
  },
);

也可以看看