JavaScript 匿名函数立即调用/执行(表达式与声明)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6719089/
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-23 22:55:28  来源:igfitidea点击:

JavaScript anonymous function immediate invocation/execution (expression vs. declaration)

javascriptanonymous-function

提问by lxa

Possible Duplicates:
What is the difference between a function expression vs declaration in JavaScript?
Explain JavaScript's encapsulated anonymous function syntax

可能的重复:
JavaScript 中的函数表达式与声明之间有什么区别?
解释 JavaScript 封装的匿名函数语法

Why this:

为什么这个:

(function () {
    //code
}());

and this:

和这个:

var f = function () {
    //code
}();

works, while this:

有效,而这个:

function () {
    //code
}();

does not? It looks exactly the same - anonymous function defined, and immediately called. Can someone make a quotation from the JavaScript/ECMAScript standard which explains that?

才不是?它看起来完全一样 - 定义了匿名函数,并立即调用。有人可以引用 JavaScript/ECMAScript 标准来解释这一点吗?

UPDATE: Thanks for the answers everyone! So it's about function expression vs. function declaration. See this Stack Overflow answer, ECMAScript standardsection 13, and this great article: Named function expressions demystified.

更新:感谢大家的回答!所以它是关于函数表达式与函数声明的。请参阅Stack Overflow 答案ECMAScript 标准第 13 节和这篇很棒的文章:命名函数表达式揭秘

To recap answers:

回顾一下答案:

  1. The first snippet is interpreted as an expression because the grouping operator, (), is applied - see ECMAScript standardsection 11.1.6.

  2. In the second snippet, the function is interpreted as an expression because it's on the right-hand part of assignment operator, =.

  3. The third snippet doesn't have anything which allows the interpreter to read the function as an expression, so it's considered a declaration, which is invalid without an identifier (Gecko lets it pass however, but it chokes on following ()grouping operator (as it thinks) applied to nothing).

  1. 第一个片段被解释为一个表达式,因为应用了分组运算符 , ()- 请参阅ECMAScript 标准第 11.1.6 节。

  2. 在第二个代码段中,该函数被解释为表达式,因为它位于赋值运算符 的右侧=

  3. 第三个代码段没有任何内容允许解释器将函数作为表达式读取,因此它被视为声明,如果没有标识符则无效(Gecko 允许它通过,但它在跟随()分组运算符时窒息(正如它认为的那样) ) 不适用)。

采纳答案by hugomg

The first two cases show function expressions, and can appear anywhere an expression like (1+1or x*f(4)) would appear. Just like how 1+1, evaluates to 2, these expressions evaluate to a corresponding function.

前两种情况显示函数表达式,并且可以出现在像 (1+1x*f(4)) 这样的表达式出现的任何地方。就像 how 1+1, 评估为 一样2,这些表达式评估为相应的函数。



The third case is a function declation statement, and can appear anywhere you can have other statements (like an ifor whilestatement).

第三种情况是一个函数声明语句,它可以出现在你可以有其他语句的任何地方(比如一个iforwhile语句)。

There is not much point in trying to declare an anonymous function via a Funcion declaration statements, since otherwise noone would get a reference to the function afterwards.

尝试通过 Funcion 声明语句声明匿名函数没有多大意义,否则之后没有人会获得对该函数的引用。



The reason you need the opening (or the var x =like in the first two cases is that they force next bit to be parsed in an expression context. (just think how you cant do var x = if ..., for example). If you just put the functionas the first thing it will be parsed as the declaration statementyou don't want.

你需要开的原因(var x =在在前两种情况下一样的是,他们迫使下位表达式上下文来解析。(var x = if ...例如,想想你怎么做不到)。如果你只是把它function作为第一件事,它会被解析为你不想要的声明语句

回答by Mark Kahn

The first two are something called a function expression, meaning it's inline and interpreted as the JS code runs.

前两个是称为函数表达式的东西,这意味着它是内联的并在 JS 代码运行时被解释。

The 3rd is a function declaration and is interpreted when the code is compiled. Since it's interpreted at compilation, you can't immediately run it since none of the other code around it has been run yet.

第三个是函数声明,在编译代码时被解释。由于它在编译时被解释,你不能立即运行它,因为它周围的其他代码还没有运行。

To show an example:

举例说明:

// foo == undefined
// bar == function

function bar(){ .. }
var foo = function(){ ... }

// foo == function
// bar == function

Put simply, any time you have the word functionwithout anything preceding it, it's a declaration. Any time something precedes it, it's an expression.

简而言之,任何时候你的词function前面没有任何东西,它就是一个声明。任何时候在它之前,它都是一个表达式。

回答by Jason Gennaro

Anonymous functions are explained well in Stack Overflow question Why do you need to invoke an anonymous function on the same line?.

匿名函数在 Stack Overflow 问题中得到了很好的解释为什么需要在同一行调用匿名函数?.

回答by Andrew

Here's a simple way to think of it: If functionis the first keyword on the line, the parser will interpret the rest of the line as a function declaration. In other words, it will think you're trying to write something like this, as if you've forgotten to name your function:

这是一个简单的思考方式:如果function是该行的第一个关键字,解析器会将行的其余部分解释为函数声明。换句话说,它会认为您正在尝试编写这样的东西,就好像您忘记了为您的函数命名:

function foo(){ 
    // code
}

The way to get around this is either to wrap the entire function inside some parens or make it part of a variable assignment. In either case, you're putting functionfurther back on the line and allowing the parser to recognize you're not writing a function declaration.

解决这个问题的方法是将整个函数包装在一些括号内,或者使其成为变量赋值的一部分。在任何一种情况下,您都将function进一步放回原处,并允许解析器识别出您没有编写函数声明。

It kind of seems trivial to me to allow functionto appear at the start of a line and still distinguish between function expressions and function declarations, but I guess it wasn't so trivial back when JavaScript was first being designed.

允许function出现在一行的开头并仍然区分函数表达式和函数声明对我来说似乎微不足道,但我想这在 JavaScript 最初被设计时并不是那么微不足道。