持續(xù)更新羡鸥,也歡迎Nodejs大牛進QQ群討論:541925216
參考網(wǎng)址:https://github.com/dead-horse/node-style-guide
https://github.com/windyrobin/iFrame/blob/master/style.md
1、使用單引號
Right:
var foo = 'bar';
var http = require('http');
Wrong:
var foo = "bar";
var http = require("http");
2司致、大括號位置
Right:
if (true) {
????console.log('winning');
}
Wrong:
if (true)
{
????console.log('losing');
}
3煞躬、文件命名采用下劃線命名法
Right:
child_process.js
string_decoder.js
_linklist.js
4肛鹏、類名采用Camel命名法
*畢竟它叫 JavaScript 而不是 java_script *
Right:
var definitionvar adminUser = db.query('SELECT * FROM users ...');
//?小駝峰
function run() {
}
//?大駝峰
function BankAccount() {
}
5、 CSS 類使用連字號
CSS 語法本身就使用連字號作為連接(比如 font-family
恩沛,text-align等
Right:
.my-class
6在扰、對象、數(shù)組的創(chuàng)建
'{}' ,'[]' 代替 new Array雷客,new Object
Right:
var a = ['hello', 'world'];
var b = {
????good: 'code',
????'is generally': 'pretty'
};
Wrong:
var a = [
????'hello', 'world'
];
var b = {"good": 'code'
, is generally: 'pretty'};
7芒珠、錯誤優(yōu)先
Node 的異步回調(diào)函數(shù)的第一個參數(shù)應(yīng)該是錯誤指示
Right:
function cb(err, data , ...) {...}
8、使用 === 比較符
Right:
var a = 0;
if (a === '') {
console.log('winning');
}
9搅裙、使用有意義的判斷條件
Right:
var isValidPassword = password.length >= 4 && /^(?=.*\d).{4,}$/.test(password);
if (isValidPassword) {
????console.log('winning');
}
Wrong:
if (password.length >= 4 && /^(?=.*\d).{4,}$/.test(password)) {
console.log('losing');
}
10妓局、盡早的從函數(shù)中返回
Right:
function isPercentage(val) {
????if (val < 0) {
????????return false;
????}
????if (val > 100) {
????????return false;
????}
????return true;
}
Wrong:
function isPercentage(val) {
????if (val >= 0) {
????????if (val < 100) {
????????????return true;
????????} else {
????????????return false;
????????}
????} else {
????????return false;
????}
}
11总放、空格縮進
使用2個空格而不是 tab 來進行代碼縮進,同時絕對不要混用空格和 tab
各個編輯器都可以進行進行偏好設(shè)置
例如:Sublime Text 設(shè)置(perfernces > Settings - User):
"tab_size": 2,
"translate_tabs_to_spaces": true
12好爬、去除行末尾的多余空格
各個編輯器都可以進行進行偏好設(shè)置
例如:Sublime Text 設(shè)置(perfernces > Settings - User):
"trim_trailing_white_space_on_save": true