Javascript 为什么函数语句需要名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8086696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:41:16  来源:igfitidea点击:

Why function statement requires a name?

javascript

提问by Stan Kurilin

Why I can write

为什么我可以写

 var foo = function(){}();

But can not

但不能

 function(){}();

Are there are any design reasons?

有什么设计原因吗?

回答by Dave Newton

The first example is an assignment: the right-hand side is an expression, and the immediate execution of an anonymous function makes sense.

第一个例子是赋值:右边是一个表达式,立即执行匿名函数是有意义的。

The second example is a declaration: once the closing "}"is hit the declaration has ended. Parens on their own don'tmake sense--they must contain an expression. The trailing ")"is an error.

第二个例子是一个声明:一旦结束"}",声明就结束了。Parens 本身没有意义——它们必须包含一个表达式。尾随")"是一个错误。

Standalone declarations must be turned into expressions:

独立声明必须转换为表达式:

(function() {})();  // Or...
(function() {}());

The first makes the declaration an expression, then executes the result. The second turns both declaration and execution into an expression.

第一个使声明成为表达式,然后执行结果。第二个将声明和执行都变成了一个表达式。

See also When do I use parenthesis and when do I not?

另请参阅何时使用括号,何时不使用?

回答by kemiller2002

You can (function(){})();, and you aren't naming the function in: var foo = function(){}();

您可以(function(){})();,并且您没有将函数命名为:var foo = function(){}();

You are setting footo the return value of the function which in your case is undefined, because all functions return something in JavaScript.

您正在设置foo函数的返回值,在您的情况下是undefined,因为所有函数都返回 JavaScript 中的某些内容。

回答by dyoo

The first use of function

函数的第一次使用

var foo = function(){}()

is in expression position, not statement position. The second one, on the other hand, is at the top-level, and works as a function statement. That is, 'function' can be used in two different contexts, and it can mean subtly different things.

在表达式位置,而不是语句位置。另一方面,第二个位于顶层,用作函数语句。也就是说,“函数”可以在两种不同的上下文中使用,并且它可能意味着微妙的不同事物。

If you want to make anonymous functions without names, you do that with a function expression. And, just because of the way JavaScript language grammar works, you'll need parens in certain context, as Dave Newton mentions, because the place where you're putting the word 'function' can be confused with its statement version (which does require a name).

如果你想创建没有名字的匿名函数,你可以使用函数表达式来实现。而且,仅仅因为 JavaScript 语言语法的工作方式,您将需要在某些上下文中使用括号,正如 Dave Newton 提到的那样,因为您放置“函数”一词的位置可能会与其语句版本混淆(这确实需要一个名字)。