为什么我应该在javascript中的每个函数后使用分号? [英] Why should I use a semicolon after every function in javascript?
问题描述
我见过不同的开发人员在javascript函数之后包含分号,而有些则没有。哪个是最佳做法?
I've seen different developers include semicolons after functions in javascript and some haven't. Which is best practice?
function weLikeSemiColons(arg) {
// bunch of code
};
或
function unnecessary(arg) {
// bunch of code
}
推荐答案
函数声明后的分号 不必。
规范中描述了 FunctionDeclaration
的语法如下:
The grammar of a FunctionDeclaration
is described in the specification as this:
function Identifier ( FormalParameterListopt ) { FunctionBody }
语法上没有分号,但可能想知道为什么?
There's no semicolon grammatically required, but might wonder why?
分号用于分隔声明彼此, FunctionDeclaration
不是声明。
Semicolons serve to separate statements from each other, and a FunctionDeclaration
is not a statement.
FunctionDeclarations
被评估 hoisting 是一个常用词,用于解释这种行为。
FunctionDeclarations
are evaluated before the code enters into execution, hoisting is a common word used to explain this behaviour.
术语函数声明和函数声明经常被错误地互换使用,因为ECMAScript规范中没有描述函数声明,但是有一些实现包含函数声明在他们的语法中, - 特别是Mozilla-但这又是非标准的。
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.
但是在使用 FunctionExpressions $ c的地方总是建议使用分号$ c>,例如:
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.
推荐讲座:
- 命名函数表达式揭秘(精彩文章)
- 解释JavaScript封装的匿名函数语法(更多内容
FunctionDeclaration
vsFunctionExpression
)
- Named function expressions demystified (great article)
- Explain JavaScript’s encapsulated anonymous function syntax (more on
FunctionDeclaration
vsFunctionExpression
)
这篇关于为什么我应该在javascript中的每个函数后使用分号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!