2012-04-06 62 views
3

我在看一个开源项目,并看到这样的事情:函数之前的分号是什么意思?

;(function(){ 
    // codes here 
})() 

我想知道是否有分号有特殊的意义?

+13

这是一个分号。如果在另一个缺少尾随分号的文件之后导入文件,可能会出现这种情况。 – Pointy 2012-04-06 14:12:16

+0

@积分谢谢。你可以将它发布在答案中,以便我可以接受它来结束这个问题。 – wong2 2012-04-06 14:15:55

回答

5

这是因为ASI(自动分号插入)允许您避免使用分号。

例如,你可以写这样的代码,并没有错误:

var a = 1 
a.fn = function() { 
    console.log(a) 
} 

看到了吗?没有一个分号。

但是,有些情况下分号未插入。基本上,在真实项目中,有一种情况不是:下一行以括号开头。

JavaScript解析器将把下一行作为参数,而不是自动添加分号。

例子:

var a = 1 
(function() {})() 
// The javascript parser will interpret this as "var a = 1(function() {})()", leading to a syntax error 

为了避免这种情况,有几种方法:

  • 在一行的开头添加一个分号用括号开始(这是在告诉你的代码完成)
  • 使用以下结构:

    !function() {}()

1

JavaScript有自动分号插入(见ECMAScript Language Specification节7.9):

There are three basic rules of semicolon insertion:

  1. When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
    • The offending token is separated from the previous token by at least one LineTerminator.
    • The offending token is } .
  2. When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript Program, then a semicolon is automatically inserted at the end of the input stream.

通常你可以省略JavaScript文件中的最后一个分号(第二条规则)。如果您的应用程序通过合并多个文件来创建JavaScript代码,则会导致语法错误。由于;本身就是空的语句,因此可以使用它来防止此类语法错误。

0

很好的解释可以在这里找到:

http://mislav.uniqpath.com/2010/05/semicolons/
(见第 “唯一真正的陷阱没有分号编码时”)

var x = y 
(a == b).print() 

被评估为

var x = y(a == b).print() 

底线,这是一个很好的做法,在每一行之前加上一个分号,以(characther 。