Semicolons after function declarations are not necessary .(函数声明后的分号不是必需的 。)
The grammar of a FunctionDeclaration
is described in the specification as this:(在规范中 , FunctionDeclaration
的语法描述如下:)
function Identifier ( FormalParameterListopt ) { FunctionBody }
There's no semicolon grammatically required, but might wonder why?(语法上没有分号,但可能想知道为什么?)
Semicolons serve to separate statements from each other, and a FunctionDeclaration
is not a statement .(分号用于将语句彼此分开,而FunctionDeclaration
不是语句 。)
FunctionDeclarations
are evaluated before the code enters into execution, hoisting is a common word used to explain this behaviour.(FunctionDeclarations
在代码进入执行之前进行评估, 起吊是用于解释此行为的常用词 。)
The terms "function declaration" and "function statement" are often wrongly used interchangeably, because there is no function statement described in the ECMAScript Specification, however there are some implementations that include a function statement in their grammar, -notably Mozilla- but again this is non-standard.(术语“函数声明”和“函数声明”通常会错误地互换使用,因为ECMAScript规范中没有描述函数声明,但是有一些实现在其语法中包括函数声明,特别是Mozilla,但是同样是非标准的。)
However semicolons are always recommended where you use FunctionExpressions
, for example:(但是,始终建议在使用FunctionExpressions
地方使用分号,例如:)
var myFn = function () {
//...
};
(function () {
//...
})();
If you omit the semicolon after the first function in the above example, you will get completely undesired results:(如果在上面的示例中的第一个函数之后省略分号,则将得到完全不希望的结果:)
var myFn = function () {
alert("Surprise!");
} // <-- No semicolon!
(function () {
//...
})();
The first function will be executed immediately, because the parentheses surrounding the second one, will be interpreted as the Arguments
of a function call.(第一个函数将立即执行,因为第二个函数的括号将被解释为函数调用的Arguments
。)
Recommended lectures:(推荐讲座:)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…