如果你不能用你给它们的名字真正引用它们,那么命名函数表达式有什么意义呢?

8 javascript

如果你不能用你给它们的名字真正引用它们,那么命名函数表达式有什么意义呢?

var f = function g() {
    console.log("test");
};

g(); // ReferenceError: g is not defined
Run Code Online (Sandbox Code Playgroud)

Roc*_*mat 11

哦,但你可以用这个名字引用它们.这些名称只存在函数的范围内.

var f = function g() {
    // In here, you can use `g` (or `f`) to reference the function
    return typeof g;
};

console.log( typeof g );
// It only exists as `f` here
console.log( f() );
Run Code Online (Sandbox Code Playgroud)

DOCS:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function#Named_function_expression

  • 注意,其中一个原因是使用`f`来引用函数是危险的 - 例如`f`可以在函数表达式之后重新定义为`null`,然后尝试在函数内调用`f()`会抛出. (3认同)

lex*_*x82 9

我发现特别有用的一个优点是它在调试时有所帮助.

发生错误时,您会在控制台的堆栈跟踪中看到函数名称.否则,堆栈跟踪中的行只会引用匿名函数.

您还可以通过为其命名来使功能更清晰.