序
继续前两篇,这篇作为终结篇。
Blocks
? 有{}的代码,我们换行处理。
// bad
if (test)
return false;
// good
if (test) return false;
// good
if (test) {
return false;
}
// bad
function() { return false; }
// good
function() {
return false;
}
Comments
? 对于多行注释使用/** … */。包含描述信息、参数类型和返回值。
// bad
// make() returns a new element
// based on the passed in tag name
//
// @param <String> tag
// @return <Element> element
function make(tag) {
// …stuff…
return element;
}
// good
/**
* make() returns a new element
* based on the passed in tag name
*
* @param <String> tag
* @return <Element> element
*/
function make(tag) {
// …stuff…
return element;
}
? 对于单行注释使用//。单行注释单独放置在一个新行上。在注释前面放置一个空行。
// bad
var active = true; // is current tab
// good
// is current tab
var active = true;
// bad
function getType() {
console.log(‘fetching type…’);
// set the default type to ‘no type’
var type = this._type ‘no type’;
return type;
}
// good
function getType() {
console.log(‘fetching type…’);
// set the default type to ‘no type’
var type = this._type ‘no type’;
return type;
}
? 对于一些问题,注释前加FIXME或TODO,这样将快速帮助开发者快速明白代码意图。
? 使用 // FIXME: 注释问题
function Calculator() {
// FIXME: shouldn’t use a global here
total = 0;
return this;
}
? 使用 // TODO: 注释问题的解决方案
function Calculator() {
// TODO: total should be configurable by an options param
this.total = 0;
return this;
}
Type Casting & Coercion
? 在声明之前执行强制类型转换。
? 字符串
// => this.reviewScore = 9;
// bad
var totalScore = this.reviewScore + ”;
// good
var totalScore = ” + this.reviewScore;
// bad
var totalScore = ” + this.reviewScore + ‘ total score’;
// good
var totalScore = this.reviewScore + ‘ total score’;
? 对于数字转换,使用parseInt,而且要带着类型转换的基数。
? 如果parseInt成为你的瓶颈,处于性能原因,需要你使用“位移”操作。那么请写下注释解释你这样做的原因。
var inputValue = ‘4’;
// bad
var val = new Number(inputValue);
// bad
var val = +inputValue;
// bad
var val = inputValue >> 0;
// bad
var val = parseInt(inputValue);
// good
var val = Number(inputValue);
// good
var val = parseInt(inputValue, 10);
// good
/**
* parseInt 使我的代码变慢.
* 为了提高速度,使用位移操作让字符串强制转化为数字。
*/
var val = inputValue >> 0;
? 布尔
var age = 0;
// bad
var hasAge = new Boolean(age);
// good
var hasAge = Boolean(age); 本文链接http://www.cxybl.com/html/wyzz/JavaScript_Ajax/20130710/39007.html
欢迎大家阅读《javascript: Javascript 风格向导(终结…_js》,跪求各位点评,若觉得好的话请收藏本文,by 搞代码