• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

javascript: Javascript 风格向导(终结_js

javascript 搞代码 7年前 (2018-06-13) 160次浏览 已收录 0个评论


  继续前两篇,这篇作为终结篇。
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 搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:javascript: Javascript 风格向导(终结_js
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址