2012-04-06 63 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 。