相信大家都知道有個Java編程規範
,
但是很少人知道Javascript也有編程規範,此規範最早由Google提出來,雖然在工程實踐上,我們對編寫Javascript還比較隨意,但是
從代碼規範性角度出發,不論何種語言都應該有自己的編程規範,否則過一段時間過後,連自己寫的代碼都不知道什麼意思了,更何況別人來看你的代碼。
雖然說這份編碼規範有待驗證,但是它由Google推出,還是具有一定的權威性和可靠性。
Google JavaScript Style
現在Google又發布了一個工具來協助你檢查 JavaScript 代碼是否嚴格遵循了 Google JavaScript Style Guide :Closure Linter
。
假設你有以下代碼:
var x = 10
var y=20;
for(var i = 0;i < 10; i++ ) {
x += i;
y -= i;
}
var z = [10, 20,];
x = y + z[0]
+ 10;
假設此檔案名稱為:fixme.js.
在命令列下運行 gjslint –strict fixme.js 之後,就會出現下面的結果:
Line 1, E:0010: (New error) Missing semicolon at end of line
Line 2, E:0002: Missing space before "="
Line 2, E:0002: Missing space after "="
Line 4, E:0002: Missing space before "("
Line 4, E:0002: Missing space after ";" in for statement
Line 4, E:0001: Extra space before ")"
Line 6, E:0006: (New error) Wrong indentation: expected any of {2} but got 3
Line 9, E:0121: Illegal comma at end of array literal
Line 12, E:0120: Binary operator should go on previous line "+"
Found 9 errors, including 2 new errors, in 1 files (0 files OK).
這個工具甚至可以幫你自動修複一些錯誤,運行 fixjsstyle –strict fixme.js 即可。(注意:不一定可以修複全部錯誤)
Closure Linter 支援 Windows, Linux & Mac OS X. 具體使用方法請看這裡
。
文章轉自:http://www.jssay.com/blog/index.php/2010/09/03/javascript%E7%BC%96%E7%A8%8B%E8%A7%84%E8%8C%83/