今天在 GitHub 上翻到一份關於「如何正確使用 JavaScript 進行開發」的規範,就拿來整理分享。原文標題是 A mostly reasonable approach to Javascript,涵蓋的項目相當完整:
Types/Objects/Arrays/Strings/Functions/Properties/Variables/Hoisting/Conditional Expressions & Equality/Blocks/Comments/Whitespace/Commas/Semicolons/Type Casting & Coercion/Naming Conventions/Accessors/Constructors/Events/Modules/jQuery/ECMAScript 5 Compatibility/Testing/Performance 等。以下摘錄幾個實用段落。
原始型別:存取時直接取得該值本身。
string / number / boolean / null / undefined
var foo = 1,
bar = foo;
bar = 9;
console.log(foo, bar); // => 1, 9
複雜型別:存取時取得的是該值的參考。
object / array / function var foo = [1, 2]; bar = foo; bar[0] = 9; console.log(foo[0], bar[0]); // => 9, 9
使用字面量建立物件:
// bad
var item = new Object();
// good
var item = {};
不要用保留關鍵字作為屬性名,這在 IE8 下會出錯:
// bad
var superman = {
default: { clark: 'kent' },
private: true
};
// good
var superman = {
defaults: { clark: 'kent' },
hidden: true
};
同樣用字面量建立:
// bad var items = new Array(); // good var items = [];
若不知道陣列長度,用內建的 push 插入:
var someStack = [];
// bad
someStack[someStack.length] = 'vein';
// good
someStack.push('vein');
需要複製陣列時,用 slice:
var len = items.length,
itemCopy = [],
i;
// bad
for (i = 0; i < len; ++i) {
itemCopy[i] = items[i];
}
// good
itemCopy = items.slice();
用單引號包圍字串:
// bad var name = "Bob Parr"; var fullName = "Bob " + this.lastName; // good var name = 'Bob Parr'; var fullName = 'Bob ' + this.lastName;
字串超過 80 字元時應跨行撰寫。要注意過度使用字串串接會影響效能:
// bad
var errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
// bad(續行反斜線)
var errorMessage = 'This is a super long error that was thrown because \
of Batman. ...';
// good
var errorMessage = 'This is a super long error that was thrown because '
+ 'of Batman. When you stop to think about how Batman '
+ 'had anything to do with this, you would get nowhere fast.';
若計畫性地組裝字串陣列,用 Array.join 效果更好:
var items, messages, length, i;
messages = [
{ stat: 'success', message: ' This one worked' },
{ stat: 'success', message: ' This one worked' },
{ stat: 'success', message: ' This one worked' }
];
length = messages.length;
// bad
function inbox(messages) {
items = '<ul>';
for (i = 0; i < length; i++) {
items += '<li>' + messages[i].message + '</li>';
}
return items + '</ul>';
}
// good
function inbox(messages) {
items = [];
for (i = 0; i < length; i++) {
items[i] = messages[i].message;
}
return '<ul><li>' + items.join('</li><li>') + '</li></ul>';
}
// 匿名函式表達式
var anonymous = function () {
return true;
};
// 命名函式表達式
var named = function named() {
return true;
};
// 立即引用函式(IIFE)
(function () {
console.log('Welcome to the Internet. Please follow me.');
})();
永遠不要在非函式的區塊(if、while)中定義函式,應把函式指派給外部變數:
// bad
if (currentUser) {
function test() {
console.log('Nope.');
}
}
// good
var test;
if (currentUser) {
test = function () {
console.log('Yup');
};
// 注意結尾的分號
}
使用點語法存取屬性:
var luke = { jedi: true, age: 28 };
// bad
var isJedi = luke['jedi'];
// good
var isJedi = luke.jedi;
當屬性名存在變數中時,才用中括號:
var luke = { jedi: true, age: 28 };
function getProp(prop) {
return luke[prop];
}
var isJedi = getProp('jedi');
這份規範的價值在於把「多數情況下合理」的選擇寫成共識,讓團隊的程式碼風格有一致依據。實際採用時建議搭配 ESLint 或 Prettier 自動化檢查,比人肉 code review 有效得多。