程式碼風格
檔案
[強制] JavaScript 原始檔必須使用不帶 BOM 的 UTF-8 編碼。
縮排
[強制] 使用 4 個空格縮排。不允許使用 Tab 或 2 個空格。
[強制] switch
中的 case
和 default
必須縮排。
// good
switch (variable) {
case '1':
// do...
break;
case '2':
// do...
break;
default:
// do...
}
// bad
switch (variable) {
case '1':
// do...
break;
case '2':
// do...
break;
default:
// do...
}
空格
[強制] 二元運算子兩側必須留一個空格。一元運算子與其運算元之間不得有空格。
let a = !arr.length;
a++;
a = b + c;
[強制] 在左花括號 {
前必須留一個空格。
// good
if (condition) {
}
set('attr', {
some: 'xxx',
any: 'yyy'
});
function funcName() {
}
// bad
if (condition){
}
set('attr',{
some: 'xxx',
any: 'yyy'
});
function funcName(){
}
[強制] 在 if
/ else
/ for
/ while
/ function
/ switch
/ do
/ try
/ catch
/ finally
之後必須留一個空格。
// good
if (condition) {
}
while (condition) {
}
(function () {
})();
// bad
if(condition) {
}
while(condition) {
}
(function() {
})();
[強制] 在物件建立語句中,:
之後必須留一個空格,但前面不能有空格。
// good
const obj = {
a: 1,
b: 2,
c: 3
};
// bad
const obj = {
a : 1,
b:2,
c :3
};
[強制] 在函式宣告、命名函式的表示式和函式呼叫中,函式名和 (
之間不得有空格。
// good
function funcName() {
}
const funcName = function funcName() {
};
funcName();
// bad
function funcName () {
}
const funcName = function funcName () {
};
funcName ();
[強制] ,
和 ;
前面不得有空格。
// good
callFunc(a, b);
// bad
callFunc(a , b) ;
[強制] (
和 [
之後以及 )
和 ]
之前不得有空格。
// good
callFunc(param1, param2, param3);
save(this.list[this.indexes[i]]);
needIncream && (variable += increament);
if (num > list.length) {
}
while (len--) {
}
// bad
callFunc( param1, param2, param3 );
save( this.list[ this.indexes[ i ] ] );
needIncreament && ( variable += increament );
if ( num > list.length ) {
}
while ( len-- ) {
}
// good
const arr1 = [];
const arr2 = [1, 2, 3];
const obj1 = {};
const obj2 = {name: 'obj'};
const obj3 = {
name: 'obj',
age: 20,
sex: 1
};
// bad
const arr1 = [ ];
const arr2 = [ 1, 2, 3 ];
const obj1 = { };
const obj2 = { name: 'obj' };
const obj3 = {name: 'obj', age: 20, sex: 1};
[強制] 每行末尾不得有多餘的空格。
換行
[強制] 語句末尾必須換行。
[強制] 每行不超過 120 個字元。
[強制] 如果語句需要換行,運算子必須放在行首。
// good
if (user.isAuthenticated()
&& user.isInRole('admin')
&& user.hasAuthority('add-admin')
|| user.hasAuthority('delete-admin')
) {
// Code
}
const result = number1 + number2 + number3
+ number4 + number5;
// bad
if (user.isAuthenticated() &&
user.isInRole('admin') &&
user.hasAuthority('add-admin') ||
user.hasAuthority('delete-admin')) {
// Code
}
const result = number1 + number2 + number3 +
number4 + number5;
[強制] 如果括號內的內容佔多行,)
、]
、}
應另起一行。其縮排與對應 (
、[
、{
所在行的縮排相同。
// good
if (product) {
product.load();
if (user.isAuthenticated()
&& user.isInRole('admin')
&& user.hasAuthority('add-admin')
) {
sendProduct(user, product);
}
}
const arr = [
'candy', 'sugar'
];
// bad
if (product) {
product.load();
if (user.isAuthenticated()
&& user.isInRole('admin')
&& user.hasAuthority('add-admin')) {
sendProduct(user, product);
}
}
const arr = [
'candy', 'sugar'
];
[強制] 不得在 ,
或 ;
前換行。
// good
const obj = {
a: 1,
b: 2,
c: 3
};
foo(
aVeryVeryLongArgument,
anotherVeryLongArgument,
callback
);
// bad
const obj = {
a: 1
, b: 2
, c: 3
};
foo(
aVeryVeryLongArgument
, anotherVeryLongArgument
, callback
);
[建議] 關於換行和縮排的建議
if (user.isAuthenticated()
&& user.isInRole('admin')
&& user.hasAuthority('add-admin')
) {
// Code
}
foo(
aVeryVeryLongArgument,
anotherVeryLongArgument,
callback
);
baidu.format(
dateFormatTemplate,
year, month, date, hour, minute, second
);
$('#items')
.find('.selected')
.highlight()
.end();
const result = thisIsAVeryVeryLongCondition
? resultA : resultB;
const res = condition
? thisIsAVeryVeryLongResult
: resultB;
[強制] 如果使用多行程式碼塊,else
和 catch
必須另起一行。
// good
if (condition) {
// some statements;
}
else {
// some statements;
}
try {
// some statements;
}
catch (ex) {
// some statements;
}
// bad
if (condition) {
// some statements;
} else {
// some statements;
}
try {
// some statements;
} catch (ex) {
// some statements;
}
語句
[強制] 語句末尾的分號不得省略。
[強制] 即使只有一行程式碼,也不得省略 {}
。
// good
if (condition) {
callFunc();
}
// bad
if (condition) callFunc();
if (condition)
callFunc();
[強制] 函式定義的末尾不得有分號。
// good
function funcName() {
}
// bad
function funcName() {
};
// For function expression, the semicolon must not be ignored.
const funcName = function () {
};
[強制] 物件和陣列宣告中不得有尾隨逗號。
// good
const obj = {
attr1: 'xxx',
attr2: 'yyy'
};
const arr = [
'xxx',
'yyy'
];
// bad
const obj = {
attr1: 'xxx',
attr2: 'yyy',
};
const arr = [
'xxx',
'yyy',
];
命名規範
[強制] 變數、屬性和函式名使用 lowerCamelCase(小駝峰命名法)。
const loadingModules = {};
function loadProduct() {
}
[強制] 類名使用 UpperCamelCase (Pascal)(大駝峰/帕斯卡命名法)。
function Element(options) {
}
[建議] 縮寫詞的所有字母應全部大寫或全部小寫。
function parseSVG() {
}
const svgParser;
語言特性
相容性
語言特性可以透過一些工具庫進行 polyfill,但絕不能透過修改 JS 內建物件的原型來實現。
// good
import * as zrUtil from 'zrender/src/core/util';
zrUtil.each(array, function (val, index) {
sum += val;
});
const result = zrUtil.map(array, function (val) {
return parse(val);
});
const pos = zrUtil.indexOf(array, val);
const obj2 = zrUtil.extend({}, obj1);
function Element() {
// ...
}
// bad
array.forEach(function (val, index) {
sum += val;
});
let result = array.map(function (val) {
return parse(val);
});
const pos = array.indexOf(val);
const obj2 = Object.assign({}, obj1);
class Element {
// ...
}
String.prototype.trim = function () {
};
變數
[強制] 優先使用 const
宣告變數。一行不能宣告多個變數。
// good
const name = 'MyName';
const hangModules = [];
const missModules = [];
const visited = {};
// bad
name = 'MyName';
const hangModules = [],
missModules = [],
visited = {};
條件
[強制] 在相等性表示式中,==
只能用於檢測 null
或 undefined
。其餘情況應使用 ===
。
// good
if (age === 30) {
// ...
}
if (type == null) {
// ...
}
// bad
if (age == 30) {
// ......
}
[建議] 使用 xxx == null
來判斷 null
或 undefined
。
[建議] 儘量使 null
和 undefined
的含義相同,即不要讓使用者或開發者區分一個變數是 null
還是 undefined
。
[建議] 函式表示式或函式宣告不應放在迴圈體內。
// good
function clicker() {
// ......
}
for (let i = 0, len = elements.length; i < len; i++) {
const element = elements[i];
addListener(element, 'click', clicker);
}
// bad
for (let i = 0, len = elements.length; i < len; i++) {
const element = elements[i];
addListener(element, 'click', function () {});
}
型別轉換
[建議] 使用 + ''
將值轉換為字串。
// good
num + '';
// bad
new String(num);
num.toString();
String(num);
[建議] 使用 +
將值轉換為數字。
// good
+str;
// bad
Number(str);
[強制] 使用 parseInt
時不得省略第二個引數。
// good
parseInt(str, 10);
// bad
parseInt(str);
字串、物件、陣列
[強制] 使用 '
而不是 "
來定義字串。
[強制] 使用物件字面量 {}
建立普通物件。
// good
const obj = {};
// bad
const obj = new Object();
[強制] 如果物件字面量的所有屬性都不需要引號,則應省略它們。如果需要引號,應使用 '
而不是 "
。
// good
const info = {
name: 'someone',
age: 28
};
// bad
const info = {
'name': 'someone',
'age': 28
};
const info2 = {
"age": 40
};
[強制] 不得修改內建物件的原型。
// Forbidden
String.prototype.trim = function () {
};
[建議] 儘量使用 .
而不是 []
來訪問物件屬性。
[建議] 在使用 for ... in ...
時應使用 hasOwnProperty
,以防某些執行時環境在 Object
的原型上添加了額外的屬性。
const newInfo = {};
for (const key in info) {
if (info.hasOwnProperty(key)) {
newInfo[key] = info[key];
}
}
[強制] 使用陣列字面量 []
建立陣列,除非意圖是建立一個具有給定長度的陣列。
// good
const arr = [];
const arr2 = new Array(1e4);
// bad
const arr = new Array();
[強制] 不要在陣列遍歷中使用 for in
。
其他
[強制] 不要使用 eval
和 with
。可以使用 new Function
。