JavaScript 编码规范(Google Coding-style for JavaScript)

来源:互联网 发布:社会 知乎 编辑:程序博客网 时间:2024/04/30 20:53
Google JS 规范

背景:

JavaScript作为一门弱类型脚本语言,其代码规范一直饱受质疑。它不像java有严格的语法规范。大家都有一套自己的JS代码规范,所以JS代码的维护及二次开发也一直是让人头痛。故规范大家的JS代码,形成统一的规范是很有必要的。这里所罗列的规范并不是官方指南,而是大家的一种共识。本文是翻译的google的coding style

链接:http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

下面从两个方面来介绍js的语法规范

一. js语法规范

1. 声明变量 必须使用var来声明变量。

 var time = 20;
2. 常量 使用大写字母,每个单词之间使用下划线分割:

 var LIMIT_PAGE_NUMBER = 20;
3. 必须以分号作为语句的结束。在js中,如果不添加分号,使用回车符,也能被浏览器识别,但是为了语法的规范,必须使用分号作为结束符。

 if(1) {time = 2;}
4. 在必要的时候,使用匿名函数。
5. 在代码块中,声明函数须有变量接收

// Not recommendedif (x) {  function foo() {}}// Recommendedif (x) {  var foo = function() {};}

6. 异常 异常在你的工作中基本上都会遇到,如果你正在做大型的项目(比如使用框架等),就大胆地使用异常处理
7. 不要将基本类型再包装成object

// Not recommendedvar x = new Boolean(false);if (x) {  alert('hi');  // Shows 'hi'.}// Recommendedvar x = Boolean(0);if (x) {  alert('hi');  // This will never be alerted.}typeof Boolean(0) == 'boolean';typeof new Boolean(0) == 'object';
8. 对象的层次结构不要太深
9. 删除
// Not recommendedFoo.prototype.dispose = function() {  delete this.property_;};// RecommendedFoo.prototype.dispose = function() {  this.property_ = null;};
10. 方法的提取 将不相关的提取在一起。
// Not recommendedfunction foo(element, a, b) {  element.onclick = function() { /* uses a and b */ };}// Recommendedfunction foo(element, a, b) {  element.onclick = bar(a, b);}function bar(a, b) {  return function() { /* uses a and b */ };}
11. 尽量少使用eval函数
12. 尽量少使用with函数
13. this关键字的使用 只允许在构造函数,方法中使用
14. for-in循环容易出错,只允许迭代key在object/map/hash中的
以下的写法经常容易出错:
function printArray(arr) {  for (var key in arr) {    print(arr[key]);  }}printArray([0,1,2,3]);  // This works.var a = new Array(10);printArray(a);  // This is wrong.a = document.getElementsByTagName('*');printArray(a);  // This is wrong.a = [0,1,2,3];a.buhu = 'wine';printArray(a);  // This is wrong again.a = new Array;a[3] = 3;printArray(a);  // This is wrong again.
//改良版本
function printArray(arr) {  var l = arr.length;  for (var i = 0; i < l; i++) {    print(arr[i]);  }}
15. 不允许将array用作map/hash/associative array
16. 多个字符串字面量
// Not recommendedvar myString = 'A rather long string of English text, an error message \                actually that just keeps going and going -- an error \                message to make the Energizer bunny blush (right through \                those Schwarzenegger shades)! Where was I? Oh yes, \                you\'ve got an error and all the extraneous whitespace is \                just gravy.  Have a nice day.';// Recommendedvar myString = 'A rather long string of English text, an error message ' +    'actually that just keeps going and going -- an error ' +    'message to make the Energizer bunny blush (right through ' +    'those Schwarzenegger shades)! Where was I? Oh yes, ' +    'you\'ve got an error and all the extraneous whitespace is ' +    'just gravy.  Have a nice day.';

17. array和object字面量

// Not recommended// Length is 3.var a1 = new Array(x1, x2, x3);// Length is 2.var a2 = new Array(x1, x2);// If x1 is a number and it is a natural number the length will be x1.// If x1 is a number but not a natural number this will throw an exception.// Otherwise the array will have one element with x1 as its value.var a3 = new Array(x1);// Length is 0.var a4 = new Array();// Recommendedvar a = [x1, x2, x3];var a2 = [x1, x2];var a3 = [x1];var a4 = [];

再比如:

// Not recommendedvar o = new Object();var o2 = new Object();o2.a = 0;o2.b = 1;o2.c = 2;o2['strange key'] = 3;// Recommendedvar o = {};var o2 = {  a: 0,  b: 1,  c: 2,  'strange key': 3};

18. 不允许修改js内置对象的prototype属性

二.js风格规范

1. 命名

functionNamesLikeThis;variableNamesLikeThis;ClassNamesLikeThis;EnumNamesLikeThis;methodNamesLikeThis;CONSTANT_VALUES_LIKE_THIS;foo.namespaceNamesLikeThis.bar;filenameslikethis.js;
2. 自己实现toString方法(和java类似)
3. 延迟初始化。
//not recommendedvar time = 23;//recommendedvar time;//toDo other action... ...time = 23;
4. 明确作用范围,在作用域链中,不要依赖于windows这个对象,有可能在另个应用中windows就不是指这个内容窗口了。
5. 代码格式化:
记得使用大括号
if (something) {  // ...} else {  // ...}
       array和object的初始化:
var arr = [1, 2, 3];  // No space after [ or before ].var obj = {a: 1, b: 2, c: 3};  // No space after { or before }.// Object initializer.var inset = {  top: 10,  right: 20,  bottom: 15,  left: 12};
数组格式化

this.rows_ = [  '"Slartibartfast" <fjordmaster@magrathea.com>',  '"Zaphod Beeblebrox" <theprez@universe.gov>',  '"Ford Prefect" <ford@theguide.com>',  '"Arthur Dent" <has.no.tea@gmail.com>',  '"Marvin the Paranoid Android" <marv@googlemail.com>',  'the.mice@magrathea.com'];// Four-space, wrap at 80.  Works with very long function names, survives// renaming without reindenting, low on space.goog.foo.bar.doThingThatIsVeryDifficultToExplain = function(    veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,    tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {  // ...};// Four-space, one argument per line.  Works with long function names,// survives renaming, and emphasizes each argument.goog.foo.bar.doThingThatIsVeryDifficultToExplain = function(    veryDescriptiveArgumentNumberOne,    veryDescriptiveArgumentTwo,    tableModelEventHandlerProxy,    artichokeDescriptorAdapterIterator) {  // ...};// Parenthesis-aligned indentation, wrap at 80.  Visually groups arguments,// low on space.function foo(veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,             tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {  // ...}// Parenthesis-aligned, one argument per line.  Emphasizes each// individual argument.function bar(veryDescriptiveArgumentNumberOne,             veryDescriptiveArgumentTwo,             tableModelEventHandlerProxy,             artichokeDescriptorAdapterIterator) {  // ...}
如果方法参数很长,并伴随有运算符时:
if (veryLongFunctionNameA(        veryLongArgumentName) ||    veryLongFunctionNameB(    veryLongArgumentName)) {  veryLongFunctionNameC(veryLongFunctionNameD(      veryLongFunctioNameE(          veryLongFunctionNameF)));}
6. 字符串的声明时,使用单引号
var msg = 'This is some HTML';
7. 添加private和protected方法注释
/** @constructor */AA_PublicClass = function() {  /** @private */  this.privateProp_ = 2;  /** @protected */  this.protectedProp = 4;};/** @private */AA_PublicClass.staticPrivateProp_ = 1;/** @protected */AA_PublicClass.staticProtectedProp = 31;/** @private */AA_PublicClass.prototype.privateMethod_ = function() {};/** @protected */AA_PublicClass.prototype.protectedMethod = function() {};
8. JS 类型
基本类型     null,underfine, boolean, number,string 
9. 注释 
js支持单行注释,和文档注释。
//Test demo 单行注释/** @constructor */project.MyClass = function() {  /**文档注释   * Maximum number of things per pane.   * @type {number}   */  this.someProperty = 4;}
10. JS Tips and Tricks
  1. True and false boolean 表达式
接下来的都是false 
nullundefined'' the empty string0 the number
但是接下来的又都是true
'0' the string[] the empty array{} the empty object
所以对于以下的写法
not recommended//not recommendedwhile (x != null) {}//recommendedwhile (x) {}//not recommendedif (y != null && y != '') {}//recommendedif (y) {}
请记得以下的boolean:
Boolean('0') == true'0' != true0 != null0 == []0 == falseBoolean(null) == falsenull != truenull != falseBoolean(undefined) == falseundefined != trueundefined != falseBoolean([]) == true[] != true[] == falseBoolean({}) == true{} != true{} != false
2. 对于&&和||
/** @param {*=} opt_win */function foo(opt_win) {  var win;  if (opt_win) {    win = opt_win;  } else {    win = window;  }  // ...}you can write this:/** @param {*=} opt_win */function foo(opt_win) {  var win = opt_win || window;  // ...}if (node) {  if (node.kids) {    if (node.kids[index]) {      foo(node.kids[index]);    }  }}you could do this:if (node && node.kids && node.kids[index]) {  foo(node.kids[index]);}or this:var kid = node && node.kids && node.kids[index];if (kid) {  foo(kid);}
3. 对于迭代
//not recommendedvar paragraphs = document.getElementsByTagName('p');for (var i = 0; i < paragraphs.length; i++) {  doSomething(paragraphs[i]);}//It is better to do this instead://recommendedvar paragraphs = document.getElementsByTagName('p');for (var i = 0, paragraph; paragraph = paragraphs[i]; i++) {  doSomething(paragraph);}

0 0
原创粉丝点击