1

我正在查看来自EcmaScript.NET的一些代码,特别是,我正在查看FunctionNode.cs中的定义。他们在定义之上提供了一个相对描述性的评论,但我不确定我下面的示例符合什么条件:

/// <summary>
/// There are three types of functions that can be defined. The first
/// is a function statement. This is a function appearing as a top-level
/// statement (i.e., not nested inside some other statement) in either a
/// script or a function.
///
/// The second is a function expression, which is a function appearing in
/// an expression except for the third type, which is...
///
/// The third type is a function expression where the expression is the
/// top-level expression in an expression statement.
///
/// The three types of functions have different treatment and must be
/// distinquished.
/// </summary>
public const int FUNCTION_STATEMENT = 1;
public const int FUNCTION_EXPRESSION = 2;
public const int FUNCTION_EXPRESSION_STATEMENT = 3;

这是我大致看到的:

<script>
(function(){document.write("The name is Bond, ")})(),
(function(){document.write("James Bond.")})()
</script>

这是否符合FUNCTION_STATEMENT, FUNCTION_EXPRESSION, FUNCTION_EXPRESSION_STATEMENT?

更新

我想我的问题是关于逗号的作用:

// Expression
(function(){ document.write('Expression1<br>'); })();
(function(){ document.write('Expression2<br>'); })();

// Expression
var showAlert=function(){ document.write('Expression3<br>'); };
showAlert();

// Declaration
function doAlert(){ document.write('Declaration<br>'); }
doAlert();

// What about this?
(function(){ document.write('What about'); })(), // <-- Note the comma
(function(){ document.write(' this?<br>'); })();

// And now this? 
var a = ((function(){ return 1; })(), // <-- Again, a comma
(function(){ return 2; })());
document.write("And now this? a = " + a);

最后两个是什么?表达式还是表达式语句?

4

1 回答 1

4

不了解 EcmaScript.NET,但据我了解,所有这些函数都是函数表达式。它们是IIFE调用的一部分,它又是逗号运算符表达式的一部分——绝不是“顶级”。

我想说第三种类型是语法上不允许的函数语句,比如

if (false) {
    function doSomething() {…}
}

查看Kangax 关于命名函数表达式的著名文章,其中总结了它们跨引擎的行为(例如 Gecko 的函数语句)。

于 2012-12-03T23:06:37.063 回答