Javascript编程规范
相信大家都知道有个Java编程规范 , 但是很少人知道Javascript也有编程规范,此规范最早由Google提出来,虽然在工程实践上,我们对编写Javascript还比较随意,但是从代码规范性角度出发,不论何种语言都应该有自己的编程规范,否则过一段时间过后,连自己写的代码都不知道什么意思了,更何况别人来看你的代码。
虽然说这份编码规范有待验证,但是它由Google推出,还是具有一定的权威性和可靠性。
现在Google又发布了一个工具来帮助你检查 JavaScript 代码是否严格遵循了 Google JavaScript Style Guide :Closure Linter 。
假设你有以下代码:
var x = 10
var y=20;
var y=20;
for(var i = 0;i < 10; i++ ) {
x += i;
y -= i;
}
x += i;
y -= i;
}
var z = [10, 20,];
x = y + z[0]
+ 10;
+ 10;
假设此文件名为:fixme.js.
在命令行下运行 gjslint –strict 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).
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. 具体使用方法请看这里。
Closure Linter 支持 Windows, Linux & Mac OS X. 具体使用方法请看这里。