问题描述
我见过不同的开发人员在 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
的语法在 规范 如下:
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
被评估在代码进入执行之前,提升是用于解释这种行为的常用词.
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
的地方总是推荐使用分号,例如:
However semicolons are always recommended where you use FunctionExpressions
, for example:
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 () {
//...
})();
第一个函数将立即执行,因为第二个函数周围的括号将被解释为函数调用的Arguments
.
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 中的每个函数后使用分号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!