本文檔的目標(biāo)是使 ENJOY 前端小組 JavaScript 代碼風(fēng)格保持一致
- 縮進(jìn)統(tǒng)一使用 4個(gè)空格做為一個(gè)縮進(jìn)層級(jí),遠(yuǎn)離 2個(gè)空格 或 tab字符吧基友們
function hello (name) {
console.log('hi', name)
}
- 單雙引號(hào)統(tǒng)一純字符串使用單引號(hào),其他雙引號(hào)
console.log('hello there')
$("<div class='box'>")
- 關(guān)鍵字后加空格
關(guān)鍵字有介么多:if / else / for / while / function / switch / do / try / catch / finally
if (condition) { ... } // ? ok
if(condition) { ... } // ? avoid
- 函數(shù)聲明、具名函數(shù)表達(dá)式中,函數(shù)名和
(之間加空格
function name (arg) { ... } // ? ok
function name(arg) { ... } // ? avoid
run(function () { ... }) // ? ok
run(function() { ... }) // ? avoid
- 二元運(yùn)算符兩側(cè)必須有一個(gè)空格,一元運(yùn)算符與操作對(duì)象之間不能有空格。
// ? ok
var x = 2
var message = 'hello, ' + name + '!'
var a = !arr.length;
a++;
// ? avoid
var x=2
var message = 'hello, '+name+'!'
var a = ! arr.length;
a + + ;
-
,后面要加空格,,前別加呀
// ? ok
var list = [1, 2, 3, 4]
function greet (name, options) { ... }
// ? avoid
var list = [1,2,3,4]
function greet (name,options) { ... }
- 語(yǔ)句換行不加
;,曉得不啦
// ? ok
var list = [1, 2, 3, 4]
function greet (name, options) { ... }
//? avoid
var list = [1, 2, 3, 4];
function greet (name, options) { ... };
- === 代替 ==
例外: obj == null ( check null || undefined)
if (name === 'John') // ? ok
if (name == 'John') // ? avoid
if (name !== 'John') // ? ok
if (name != 'John') // ? avoid
- 對(duì)于 if...else...,在else前不要添加一個(gè)換行
// ? ok
if (condition) {
// ...
} else {
// ...
}
// ? avoid
if (condition) {
// ...
}
else {
// ...
}
- 在 if...else... 語(yǔ)句中,如果有多行,請(qǐng)使用省略塊{...} , 一行的可以不用撒
// ? ok
if (options.quiet !== true) console.log('done')
// ? ok
if (options.quiet !== true) {
console.log('done')
}
// ? avoid
if (options.quiet !== true)
console.log('done')
- 報(bào)錯(cuò)要處理昂
// ? ok
run(function (err) {
if (err) throw err
window.alert('done')
})
// ? avoid
run(function (err) {
window.alert('done')
})
- 多余的換行是不允許滴
// ? ok
var value = 'hello world'
console.log(value)
// ? avoid
var value = 'hello world'
換行
換行
換行(打不出來,自行腦補(bǔ)可以伐?
console.log(value)
- 對(duì)于三目運(yùn)算如果有多行,
?和:請(qǐng)放在語(yǔ)句前面,
// ? ok
var location = env.development ? 'localhost' : 'www.api.com'
// ? ok
var location = env.development
? 'localhost'
: 'www.api.com'
// ? avoid
var location = env.development ?
'localhost' :
'www.api.com'
-
(,[,、,如果以這三個(gè)符號(hào)為開頭,符號(hào)前加上;
// ? ok
;(function () {
window.alert('ok')
}())
// ? ok
;[1, 2, 3].forEach(bar)
// ? ok
;`hello`.indexOf('o')
// ? avoid
(function () {
window.alert('ok')
}())
// ? avoid
[1, 2, 3].forEach(bar)
// ? avoid
`hello`.indexOf('o')
當(dāng)然,我們一般這么做:
var nums = [1, 2, 3]
nums.forEach(bar)
替換
;[1, 2, 3].forEach(bar)