且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将命名函数存储在具有不同名称的变量中

更新时间:2023-02-23 21:49:51

当您使用这样的命名函数表达式(NFE)时,函数的名称仅在 函数范围内:

When you use a named function expression (NFE) like that, the function's name is only in scope within the function:

var x = function z(){
    console.log(typeof z); // "function"
};
x();
console.log(typeof z);     // "undefined"

这是两者之间的重大差异之一命名函数表达式和函数声明:NFE不会将函数的名称添加到表达式出现的作用域中;声明 将声明的名称添加到声明出现的范围。 (它们也会在不同的时间发生,等等;我会详细介绍创建函数的各种方法以及它们的工作原理在其他答案中。)

This is one of the big differences between a named function expression and a function declaration: An NFE doesn't add the function's name to the scope in which the expression appears; a declaration does add the function's name to the scope in which the declaration appears. (They also happen at different times, etc.; I do a rundown of the various ways of creating functions and how they work in this other answer.)

这样做有几个原因:


  • 它允许函数调用自身(通过其名称)而不依赖于变量,适用于递归有用的情况。

  • It lets the function call itself (via its name) without relying on the variable, for situations where recursion is useful.

在ES5中之前,它为您提供了一种为函数命名的方法(用于堆栈跟踪和类似)。 (在ES2015 +中,即使您在大多数情况下使用匿名表达式,该函数也会有一个名称;该名称是根据表达式设置的。)

In ES5 and earlier, it gave you a way to give the function a name (for stack traces and similar). (In ES2015+, the function will have a name even if you use an anonymous expression is most cases; the name is set based on the expression.)

In ES2015 +,它允许您为函数赋予与从表达式推断出的函数不同的名称。

In ES2015+, it lets you give the function a different name from the one that would be inferred from the expression.