Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

javascript - 为什么要在javascript中的每个函数之后使用分号?(Why should I use a semicolon after every function in javascript?)

I've seen different developers include semicolons after functions in javascript and some haven't.(我已经看到不同的开发人员在javascript函数中包含分号,而有些还没有。)

Which is best practice?(哪个是最佳做法?)
function weLikeSemiColons(arg) {
   // bunch of code
};

or(要么)

function unnecessary(arg) {
  // bunch of code
}
  ask by macca1 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:(推荐讲座:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...