Require or disallow named function expressions (func-names)

要求或禁止命名的 function 表达式 (func-names)

A pattern that’s becoming more common is to give function expressions names to aid in debugging. For example:

给函数表达式加个名字可以方便调试,这种模式越来越普遍。例如:

Foo.prototype.bar = function bar() {};

Adding the second bar in the above example is optional. If you leave off the function name then when the function throws an exception you are likely to get something similar to anonymous function in the stack trace. If you provide the optional name for a function expression then you will get the name of the function expression in the stack trace.

在上面的例子中添加第二个 bar是可选的。如果不使用函数名的话,当该函数抛出异常时,你可能得到一些类似于堆栈里 anonymous function 的东西。如果你为函数表达式提供了可选名称,你将在堆栈中找到该函数表达式的名称。

Rule Details

This rule can enforce or disallow the use of named function expressions.

该规则要求或禁止命名的 function 表达式。

Options

This rule has a string option:

该规则有一个字符串选项:

always

Examples of incorrect code for this rule with the default "always" option:

默认选项 "always"错误 代码示例:

/*eslint func-names: ["error", "always"]*/

Foo.prototype.bar = function() {};

(function() {
    // ...
}())

Examples of correct code for this rule with the default "always" option:

默认选项 "always"正确 代码示例:

/*eslint func-names: ["error", "always"]*/

Foo.prototype.bar = function bar() {};

(function bar() {
    // ...
}())

as-needed

ECMAScript 6 introduced a name property on all functions. The value of name is determined by evaluating the code around the function to see if a name can be inferred. For example, a function assigned to a variable will automatically have a name property equal to the name of the variable. The value of name is then used in stack traces for easier debugging.

ECMAScript 6 的所有函数中都有一个 name 属性。name值是根据函数的代码来推断的。比如,一个函数赋值给一个变量将会自动有一个 name 属性等同于变量的名称。在堆栈跟踪中使用 name值,更容易调试。

Examples of incorrect code for this rule with the "as-needed" option:

选项 "as-needed"错误 代码示例:

/*eslint func-names: ["error", "as-needed"]*/

Foo.prototype.bar = function() {};

(function() {
    // ...
}())

Examples of correct code for this rule with the "as-needed" option:

选项 "as-needed"正确 代码示例:

/*eslint func-names: ["error", "as-needed"]*/

var bar = function() {};

(function bar() {
    // ...
}())

never

Examples of incorrect code for this rule with the "never" option:

选项 "never"错误 代码示例:

/*eslint func-names: ["error", "never"]*/

Foo.prototype.bar = function bar() {};

(function bar() {
    // ...
}())

Examples of correct code for this rule with the "never" option:

选项 "never"正确 代码示例:

/*eslint func-names: ["error", "never"]*/

Foo.prototype.bar = function() {};

(function() {
    // ...
}())

Further Reading

Compatibility

Version

This rule was introduced in ESLint 0.4.0.

该规则在 ESLint 0.4.0 中被引入。

Resources