为什么函数语句需要一个名字? [英] Why function statement requires a name?
本文介绍了为什么函数语句需要一个名字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我可以写
var foo = function(){}();
但不能
function(){}();
是否有任何设计理由?
推荐答案
第一个例子是赋值:右侧是一个表达式,并且匿名函数的立即执行是有意义的。
The first example is an assignment: the right-hand side is an expression, and the immediate execution of an anonymous function makes sense.
第二个例子是声明:一旦结束}
,声明就结束了。 Parens自己不有意义 - 它们必须包含一个表达式。尾随)
是一个错误。
The second example is a declaration: once the closing "}"
is hit the declaration has ended. Parens on their own don't make sense--they must contain an expression. The trailing ")"
is an error.
独立声明必须转换为表达式:
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.
这篇关于为什么函数语句需要一个名字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文