Airbnb 是一家位於美國舊金山的公司,本文是其內部的 JavaScript 風格指南/編碼規範,在 Github 上有 11,000+ Star,2100+ fork,前端開發者可參考。
基本類型
- 當你訪問基本類型時,你是直接對它的值進行操作。
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不能運行。More info
// bad
var superman = {
default: { clark: 'kent' },
private: true
};
// good
var superman = {
defaults: { clark: 'kent' },
hidden: true
};
- 使用容易理解的同義詞來替代保留字
// bad
var superman = {
class: 'alien'
};
// bad
var superman = {
klass: 'alien'
};
// good
var superman = {
type: 'alien'
};
-
數組
- 使用字面量語法來創建數組
// bad
var items = new Array();
// good
var items = [];
- 如果你不知道數組長度,數組添加成員使用push方法。
var someStack = [];
// bad
someStack[someStack.length] = 'abracadabra';
// good
someStack.push('abracadabra');
- 當你需要複製一個數組時,使用數組的slice方法。jsPerf
var len = items.length,
itemsCopy = [],
i;
// bad
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
// good
itemsCopy = items.slice();
- 當你需要把“類似數組對象”轉爲數組時,使用數組的slice方法。
function trigger() {
var args = Array.prototype.slice.call(arguments);
...
}
-
字符串
- 字符串使用單引號‘’
// bad
var name = "Bob Parr";
// good
var name = 'Bob Parr';
// bad
var fullName = "Bob " + this.lastName;
// good
var fullName = 'Bob ' + this.lastName;
- 大於80個元素的字符串需要通過分隔符進行多行操作。
- 注意:如果在長字符串中過度使用分隔符會影響性能。. jsPerf & Discussion
// 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. When you stop to think about how Batman had anything to do
with this, you would get nowhere
fast.';
// 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.';
- 通過編程的方式創建字符串,應該使用數組的join方法,而不是字符串鏈接方法。特別是對於IE而言。 jsPerf.
var items,
messages,
length,
i;
messages = [{
state: 'success',
message: 'This one worked.'
}, {
state: 'success',
message: 'This one worked as well.'
}, {
state: 'error',
message: 'This one did not work.'
}];
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>';
-
函數
- 函數表達式
// anonymous function expression
var anonymous = function() {
return true;
};
// named function expression
var named = function named() {
return true;
};
// immediately-invoked function expression (IIFE)
(function() {
console.log('Welcome to the Internet. Please follow me.');
})();
- 不要直接在非函數塊(if,while等)裏聲明一個函數,最好將函數賦值給一個變量。雖然瀏覽器允許你在非函數塊中聲明函數,但是由於不同的瀏覽器對Javascript的解析方式不同,這樣做就很可能造成麻煩。
- 注意:ECMA-262 將塊定義爲一組語句,而函數聲明不是語句。Read ECMA-262′s note on this issue
// bad
if (currentUser) {
function test() {
console.log('Nope.');
}
}
// good
var test;
if (currentUser) {
test = function test() {
console.log('Yup.');
};
}
- 不要將參數命名爲arguments,它將在每個函數的作用範圍內優先於arguments對象。
// bad
function nope(name, options, arguments) {
// ...stuff...
}
// good
function yup(name, options, args) {
// ...stuff...
}
-
屬性
- 使用點符號 . 來訪問屬性
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');
-
變量
- 使用var來聲明變量,否則將聲明全局變量,我們需要儘量避免污染全局命名空間,Captain Planet這樣警告過我們。
// bad
superPower = new SuperPower();
// good
var superPower = new SuperPower();
- 多個變量時只使用一個var聲明,每個變量佔一新行。
// bad
var items = getItems();
var goSportsTeam = true;
var dragonball = 'z';
// good
var items = getItems(),
goSportsTeam = true,
dragonball = 'z';
- 最後再聲明未賦值的變量,這對你之後需要依賴之前變量的變量賦值會有幫助。
// bad
var i, len, dragonball,
items = getItems(),
goSportsTeam = true;
// bad
var i, items = getItems(),
dragonball,
goSportsTeam = true,
len;
// good
var items = getItems(),
goSportsTeam = true,
dragonball,
length,
i;
- 在範圍內將變量賦值置頂,這有助於避免變量聲明和賦值提升相關的問題
// bad
function() {
test();
console.log('doing stuff..');
//..other stuff..
var name = getName();
if (name === 'test') {
return false;
}
return name;
}
// good
function() {
var name = getName();
test();
console.log('doing stuff..');
//..other stuff..
if (name === 'test') {
return false;
}
return name;
}
// bad
function() {
var name = getName();
if (!arguments.length) {
return false;
}
return true;
}
// good
function() {
if (!arguments.length) {
return false;
}
var name = getName();
return true;
}
來源 http://blog.jobbole.com/79484/