Skip to content

appleboy/javascript

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Airbnb JavaScript Style Guide() {

一份彙整了在 JavasScript 中被普遍使用的風格指南。

Downloads ![Gitter](https://badges.gitter.im/Join Chat.svg)

其他風格指南

翻譯自 Airbnb JavaScript Style Guide

目錄

  1. 資料型態
  2. 參考
  3. 物件
  4. 陣列
  5. 解構子
  6. 字串
  7. 函式
  8. 箭頭函式
  9. 建構子
  10. 模組
  11. 迭代器及產生器
  12. 屬性
  13. 變數
  14. 提升
  15. 條件式與等號
  16. 區塊
  17. 註解
  18. 空格
  19. 逗號
  20. 分號
  21. 型別轉換
  22. 命名規則
  23. 存取器
  24. 事件
  25. jQuery
  26. ECMAScript 5 相容性
  27. ECMAScript 6 風格
  28. 測試
  29. 效能
  30. 資源
  31. 誰在使用
  32. 翻譯
  33. JavaScript 風格指南
  34. 和我們討論 Javascript
  35. 貢獻者
  36. 授權許可

資料型態

  • 1.1 基本:你可以直接存取基本資料型態。

    • 字串
    • 數字
    • 布林
    • null
    • undefined
    const foo = 1;
    let bar = foo;
    
    bar = 9;
    
    console.log(foo, bar); // => 1, 9
  • 1.2 複合:你需要透過引用的方式存取複合資料型態。

    • 物件
    • 陣列
    • 函式
    const foo = [1, 2];
    const bar = foo;
    
    bar[0] = 9;
    
    console.log(foo[0], bar[0]); // => 9, 9

⬆ 回到頂端

參考

  • 2.1 對於所有的參考使用 const;避免使用 var

為什麼?因為這能確保你無法對參考重新賦值,也不會讓你的程式碼有錯誤或難以理解。

```javascript
// bad
var a = 1;
var b = 2;

// good
const a = 1;
const b = 2;
```
  • 2.2 如果你需要可變動的參考,使用 let 代替 var

為什麼?因為 let 的作用域是在區塊內,而不像 var 是在函式內。

```javascript
// bad
var count = 1;
if (true) {
  count += 1;
}

// good, use the let.
let count = 1;
if (true) {
  count += 1;
}
```
  • 2.3 請注意,letconst 的作用域都只在區塊內。

    // const 及 let 只存在於他們被定義的區塊內。
    {
      let a = 1;
      const b = 1;
    }
    console.log(a); // ReferenceError
    console.log(b); // ReferenceError

⬆ 回到頂端

物件

  • 3.1 使用簡潔的語法建立物件。

    // bad
    const item = new Object();
    
    // good
    const item = {};
  • 3.2 別使用保留字 當作鍵值,他在 IE8 上不會被執行。了解更多。不過在 ES6 模組及伺服器端程式碼中使用是可行的。

    // bad
    const superman = {
      default: { clark: 'kent' },
      private: true,
    };
    
    // good
    const superman = {
      defaults: { clark: 'kent' },
      hidden: true,
    };
  • 3.3 使用同義詞取代保留字。

    // bad
    const superman = {
      class: 'alien',
    };
    
    // bad
    const superman = {
      klass: 'alien',
    };
    
    // good
    const superman = {
      type: 'alien',
    };

  • 3.4 建立具有動態屬性名稱的物件時請使用可被計算的屬性名稱。

為什麼?因為這樣能夠讓你在同一個地方定義所有的物件屬性。

```javascript

function getKey(k) {
  return `a key named ${k}`;
}

// bad
const obj = {
  id: 5,
  name: 'San Francisco',
};
obj[getKey('enabled')] = true;

// good
const obj = {
  id: 5,
  name: 'San Francisco',
  [getKey('enabled')]: true,
};
```

  • 3.5 使用物件方法的簡寫。

    // bad
    const atom = {
      value: 1,
    
      addValue: function (value) {
        return atom.value + value;
      },
    };
    
    // good
    const atom = {
      value: 1,
    
      addValue(value) {
        return atom.value + value;
      },
    };

  • 3.6 使用屬性值的簡寫

為什麼?因為寫起來更短且更有描述性。

```javascript
const lukeSkywalker = 'Luke Skywalker';

// bad
const obj = {
  lukeSkywalker: lukeSkywalker,
};

// good
const obj = {
  lukeSkywalker,
};
```
  • 3.7 請在物件宣告的開頭將簡寫的屬性分組。

為什麼?因為這樣能夠很簡單的看出哪些屬性是使用簡寫。

```javascript
const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';

// bad
const obj = {
  episodeOne: 1,
  twoJediWalkIntoACantina: 2,
  lukeSkywalker,
  episodeThree: 3,
  mayTheFourth: 4,
  anakinSkywalker,
};

// good
const obj = {
  lukeSkywalker,
  anakinSkywalker,
  episodeOne: 1,
  twoJediWalkIntoACantina: 2,
  episodeThree: 3,
  mayTheFourth: 4,
};
```

⬆ 回到頂端

陣列

  • 4.1 使用簡潔的語法建立陣列。

    // bad
    const items = new Array();
    
    // good
    const items = [];
  • 4.2 如果你不知道陣列的長度請使用 Array#push。

    const someStack = [];
    
    // bad
    someStack[someStack.length] = 'abracadabra';
    
    // good
    someStack.push('abracadabra');

  • 4.3 使用陣列的擴展運算子 ... 來複製陣列。

    // bad
    const len = items.length;
    const itemsCopy = [];
    let i;
    
    for (i = 0; i < len; i++) {
      itemsCopy[i] = items[i];
    }
    
    // good
    const itemsCopy = [...items];
  • 4.4 如果要轉換一個像陣列的物件至陣列,可以使用 Array#from。

    const foo = document.querySelectorAll('.foo');
    const nodes = Array.from(foo);

⬆ 回到頂端

解構子

  • 5.1 存取或使用多屬性的物件時,請使用物件解構子。

為什麼?因為解構子能夠節省你對這些屬性建立暫時的參考。

```javascript
// bad
function getFullName(user) {
  const firstName = user.firstName;
  const lastName = user.lastName;

  return `${firstName} ${lastName}`;
}

// good
function getFullName(obj) {
  const { firstName, lastName } = obj;
  return `${firstName} ${lastName}`;
}

// best
function getFullName({ firstName, lastName }) {
  return `${firstName} ${lastName}`;
}
```
  • 5.2 使用陣列解構子。

    const arr = [1, 2, 3, 4];
    
    // bad
    const first = arr[0];
    const second = arr[1];
    
    // good
    const [first, second] = arr;
  • 5.3 需要回傳多個值時請使用物件解構子,而不是陣列解構子。

為什麼?因為你可以增加新的屬性或改變排序且不須更動呼叫的位置。

```javascript
// bad
function processInput(input) {
  // 這時神奇的事情出現了
  return [left, right, top, bottom];
}

// 呼叫時必須考慮回傳資料的順序。
const [left, __, top] = processInput(input);

// good
function processInput(input) {
  // 這時神奇的事情出現了
  return { left, right, top, bottom };
}

// 呼叫時只需選擇需要的資料
const { left, right } = processInput(input);
```

⬆ 回到頂端

字串

  • 6.1 字串請使用單引號 ''

    // bad
    const name = "Capt. Janeway";
    
    // good
    const name = 'Capt. Janeway';
  • 6.2 如果字串超過 100 個字元,請使用字串連接符號換行。

  • 6.3 注意:過度的長字串連接可能會影響效能 jsPerf討論串

    // bad
    const 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
    const 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
    const 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.';

  • 6.4 當以程式方式建構字串時,請使用模板字串而不是字串連接。

為什麼?因為模板字串更有可讀性,正確的換行符號及字串插值功能讓語法更簡潔。

```javascript
// bad
function sayHi(name) {
  return 'How are you, ' + name + '?';
}

// bad
function sayHi(name) {
  return ['How are you, ', name, '?'].join();
}

// good
function sayHi(name) {
  return `How are you, ${name}?`;
}
```
  • 6.5 千萬不要在字串中使用 eval(),會造成許多的漏洞。

⬆ 回到頂端

函式

  • 7.1 使用函式宣告而不是函式表達式。

為什麼?因為函式宣告是可命名的,所以他們在呼叫堆疊中更容易被識別。此外,函式宣告自身都會被提升,而函式表達式則只有參考會被提升。這個規則使得箭頭函式可以完全取代函式表達式。

```javascript
// bad
const foo = function () {
};

// good
function foo() {
}
```
  • 7.2 函式表達式:

    // 立即函式(IIFE)
    (() => {
      console.log('Welcome to the Internet. Please follow me.');
    })();
  • 7.3 絕對不要在非函式的區塊(if, while, 等等)宣告函式,瀏覽器或許會允許你這麼做,但不同瀏覽器產生的結果可能會不同。你可以將函式賦予一個區塊外的變數解決這個問題。

  • 7.4 注意: ECMA-262 將 區塊 定義為陳述式,函式宣告則不是陳述式。閱讀 ECMA-262 關於這個問題的說明

    // bad
    if (currentUser) {
      function test() {
        console.log('Nope.');
      }
    }
    
    // good
    let test;
    if (currentUser) {
      test = () => {
        console.log('Yup.');
      };
    }
  • 7.5 請勿將參數命名為 arguments ,這樣會將覆蓋掉函式作用域傳來的 arguments

    // bad
    function nope(name, options, arguments) {
      // ...stuff...
    }
    
    // good
    function yup(name, options, args) {
      // ...stuff...
    }

  • 7.6 絕對不要使用 arguments,可以選擇使用 rest 語法 ... 替代。

為什麼?使用 ... 能夠明確指出你要皆參數傳入哪個變數。再加上 rest 參數是一個真正的陣列,而不像 arguments 似陣列而非陣列。

```javascript
// bad
function concatenateAll() {
  const args = Array.prototype.slice.call(arguments);
  return args.join('');
}

// good
function concatenateAll(...args) {
  return args.join('');
}
```

  • 7.7 使用預設參數的語法,而不是變動函式的參數。

    // really bad
    function handleThings(opts) {
      // 不!我們不該變動函式的參數。
      // Double bad: 如果 opt 是 false ,那們它就會被設定為一個物件,
      // 或許你想要這麼做,但是這樣可能會造成一些 Bug。
      opts = opts || {};
      // ...
    }
    
    // still bad
    function handleThings(opts) {
      if (opts === void 0) {
        opts = {};
      }
      // ...
    }
    
    // good
    function handleThings(opts = {}) {
      // ...
    }
  • 7.8 使用預設參數時請避免副作用。

為什麼?因為這樣會讓思緒混淆。

var b = 1;
// bad
function count(a = b++) {
  console.log(a);
}
count();  // 1
count();  // 2
count(3); // 3
count();  // 3
  • 7.9 永遠將預設參數放置於最後。

    // bad
    function handleThings(opts = {}, name) {
      // ...
    }
    
    // good
    function handleThings(name, opts = {}) {
      // ...
    }
  • 7.10 千萬別使用建構函式去建立一個新的函式。

    為什麼?透過這種方式建立一個函數來計算字串類似於 eval(),會造成許多的漏洞。

    // bad
    var add = new Function('a', 'b', 'return a + b');
    
    // still bad
    var subtract = Function('a', 'b', 'return a - b');

⬆ 回到頂端

箭頭函式

  • 8.1 當你必須使用函式表達式(或傳遞一個匿名函式)時,請使用箭頭函式的符號。

為什麼?它會在有 this 的內部建立了一個新版本的函式,通常功能都是你所想像的,而且語法更為簡潔。

為什麼不?如果你已經有一個相當複雜的函式時,或許你該將邏輯都移到一個函式宣告上。

```javascript
// bad
[1, 2, 3].map(function (x) {
  const y = x + 1;
  return x * y;
});

// good
[1, 2, 3].map((x) => {
  const y = x + 1;
  return x * y;
});
```
  • 8.2 如果函式適合只使用一行,你可以很隨性的省略大括號及使用隱藏的回傳。否則請使用 return 語法。

為什麼?因為語法修飾。這樣能夠在多個函式鏈結在一起的時候更易讀。

為什麼不?如果你打算回傳一個物件。

```javascript
// good
[1, 2, 3].map(number => `A string containing the ${number}.`);

// bad
[1, 2, 3].map(number => {
  const nextNumber = number + 1;
  `A string containing the ${nextNumber}.`;
});

// good
[1, 2, 3].map(number => {
  const nextNumber = number + 1;
  return `A string containing the ${nextNumber}.`;
});
```
  • 8.3 如果表達式跨了多行,請將它們包在括號中增加可讀性。

為什麼?這麼做更清楚的表達函式的開始與結束的位置。

```js
// bad
[1, 2, 3].map(number => 'As time went by, the string containing the ' +
  `${number} became much longer. So we needed to break it over multiple ` +
  'lines.'
);

// good
[1, 2, 3].map(number => (
  `As time went by, the string containing the ${number} became much ` +
  'longer. So we needed to break it over multiple lines.'
));
```
  • 8.4 如果你的函式只使用一個參數,那麼可以很隨意的省略括號。

為什麼?減少視覺上的混亂。

```js
// good
[1, 2, 3].map(x => x * x);

// good
[1, 2, 3].reduce((y, x) => x + y);
```

⬆ 回到頂端

建構子

  • 9.1 總是使用 class。避免直接操作 prototype

為什麼?因為 class 語法更簡潔且更易讀。

```javascript
// bad
function Queue(contents = []) {
  this._queue = [...contents];
}
Queue.prototype.pop = function() {
  const value = this._queue[0];
  this._queue.splice(0, 1);
  return value;
}


// good
class Queue {
  constructor(contents = []) {
    this._queue = [...contents];
  }
  pop() {
    const value = this._queue[0];
    this._queue.splice(0, 1);
    return value;
  }
}
```
  • 9.2 使用 extends 繼承。

為什麼?因為他是一個內建繼承原型方法的方式,且不會破壞 instanceof

```javascript
// bad
const inherits = require('inherits');
function PeekableQueue(contents) {
  Queue.apply(this, contents);
}
inherits(PeekableQueue, Queue);
PeekableQueue.prototype.peek = function() {
  return this._queue[0];
}

// good
class PeekableQueue extends Queue {
  peek() {
    return this._queue[0];
  }
}
```
  • 9.3 方法可以回傳 this 幫助方法鏈結。

    // bad
    Jedi.prototype.jump = function() {
      this.jumping = true;
      return true;
    };
    
    Jedi.prototype.setHeight = function(height) {
      this.height = height;
    };
    
    const luke = new Jedi();
    luke.jump(); // => true
    luke.setHeight(20); // => undefined
    
    // good
    class Jedi {
      jump() {
        this.jumping = true;
        return this;
      }
    
      setHeight(height) {
        this.height = height;
        return this;
      }
    }
    
    const luke = new Jedi();
    
    luke.jump()
      .setHeight(20);
  • 9.4 可以寫一個 toString() 的方法,但是請確保它可以正常執行且沒有函式副作用。

    class Jedi {
      constructor(options = {}) {
        this.name = options.name || 'no name';
      }
    
      getName() {
        return this.name;
      }
    
      toString() {
        return `Jedi - ${this.getName()}`;
      }
    }

⬆ 回到頂端

模組

  • 10.1 總是使用模組(import/export)勝過一個非標準模組的系統。你可以編譯為喜歡的模組系統。

為什麼?模組就是未來的趨勢,讓我們現在就開始前往未來吧。

```javascript
// bad
const AirbnbStyleGuide = require('./AirbnbStyleGuide');
module.exports = AirbnbStyleGuide.es6;

// ok
import AirbnbStyleGuide from './AirbnbStyleGuide';
export default AirbnbStyleGuide.es6;

// best
import { es6 } from './AirbnbStyleGuide';
export default es6;
```
  • 10.2 請別使用萬用字元引入。

為什麼?這樣能夠確保你只有一個預設導出。

```javascript
// bad
import * as AirbnbStyleGuide from './AirbnbStyleGuide';

// good
import AirbnbStyleGuide from './AirbnbStyleGuide';
```
  • 10.3 然後也不要在引入的地方導出。

為什麼?雖然一行程式相當的簡明,但是讓引入及導出各自有明確的方式能夠讓事情保持一致。

```javascript
// bad
// filename es6.js
export { es6 as default } from './airbnbStyleGuide';

// good
// filename es6.js
import { es6 } from './AirbnbStyleGuide';
export default es6;
```

⬆ 回到頂端

迭代器及產生器

  • 11.1 不要使用迭代器。更好的做法是使用 JavaScript 的高階函式,像是 map()reduce(),替代如 for-of 的迴圈語法。

為什麼?這加強了我們不變的規則。處理純函式的回傳值讓程式碼更易讀,勝過它所造成的函式副作用。

```javascript
const numbers = [1, 2, 3, 4, 5];

// bad
let sum = 0;
for (let num of numbers) {
  sum += num;
}

sum === 15;

// good
let sum = 0;
numbers.forEach((num) => sum += num);
sum === 15;

// best (使用 javascript 的高階函式)
const sum = numbers.reduce((total, num) => total + num, 0);
sum === 15;
```
  • 11.2 現在還不要使用產生器。

為什麼?因為它現在編譯至 ES5 還沒有編譯得非常好。

⬆ 回到頂端

屬性

  • 12.1 使用點 . 來存取屬性。

    const luke = {
      jedi: true,
      age: 28,
    };
    
    // bad
    const isJedi = luke['jedi'];
    
    // good
    const isJedi = luke.jedi;
  • 12.2 需要帶參數存取屬性時請使用中括號 []

    const luke = {
      jedi: true,
      age: 28,
    };
    
    function getProp(prop) {
      return luke[prop];
    }
    
    const isJedi = getProp('jedi');

⬆ 回到頂端

變數

  • 13.1 為了避免污染全域的命名空間,請使用 const 來宣告變數,如果不這麼做將會產生全域變數。Captain Planet warned us of that.

    // bad
    superPower = new SuperPower();
    
    // good
    const superPower = new SuperPower();
  • 13.2 每個變數只使用一個 const 來宣告。

    為什麼?因為這樣更容易增加新的變數宣告,而且你也不用擔心替換 ;, 及加入的標點符號不同的問題。

    // bad
    const items = getItems(),
        goSportsTeam = true,
        dragonball = 'z';
    
    // bad
    // (比較上述例子找出錯誤)
    const items = getItems(),
        goSportsTeam = true;
        dragonball = 'z';
    
    // good
    const items = getItems();
    const goSportsTeam = true;
    const dragonball = 'z';
  • 13.3 將所有的 constlet 分組。

為什麼?當你需要根據之前已賦值的變數來賦值給未賦值變數時相當有幫助。

```javascript
// bad
let i, len, dragonball,
    items = getItems(),
    goSportsTeam = true;

// bad
let i;
const items = getItems();
let dragonball;
const goSportsTeam = true;
let len;

// good
const goSportsTeam = true;
const items = getItems();
let dragonball;
let i;
let length;
```
  • 13.4 在你需要的地方賦值給變數,但是請把它們放在合理的位置。

為什麼?因為 letconst 是在區塊作用域內,而不是函式作用域。

```javascript
// good
function() {
  test();
  console.log('doing stuff..');

  //..other stuff..

  const name = getName();

  if (name === 'test') {
    return false;
  }

  return name;
}

// bad - 呼叫不必要的函式
function(hasName) {
  const name = getName();

  if (!hasName) {
    return false;
  }

  this.setFirstName(name);

  return true;
}

// good
function(hasName) {
  if (!hasName) {
    return false;
  }

  const name = getName();
  this.setFirstName(name);

  return true;
}
```

⬆ 回到頂端

提升

  • 14.1 var 宣告可以被提升至該作用域的最頂層,但賦予的值並不會。constlet 的宣告被賦予了新的概念,稱為暫時性死區(Temporal Dead Zones, TDZ)。這對於瞭解為什麼 typeof 不再那麼安全是相當重要的。

    // 我們知道這樣是行不通的
    // (假設沒有名為 notDefined 的全域變數)
    function example() {
      console.log(notDefined); // => throws a ReferenceError
    }
    
    // 由於變數提升的關係,
    // 你在引用變數後再宣告變數是行得通的。
    // 注:賦予給變數的 `true` 並不會被提升。
    function example() {
      console.log(declaredButNotAssigned); // => undefined
      var declaredButNotAssigned = true;
    }
    
    // 直譯器會將宣告的變數提升至作用域的最頂層,
    // 表示我們可以將這個例子改寫成以下:
    function example() {
      let declaredButNotAssigned;
      console.log(declaredButNotAssigned); // => undefined
      declaredButNotAssigned = true;
    }
    
    // 使用 const 及 let
    function example() {
      console.log(declaredButNotAssigned); // => throws a ReferenceError
      console.log(typeof declaredButNotAssigned); // => throws a ReferenceError
      const declaredButNotAssigned = true;
    }
  • 14.2 賦予匿名函式的變數會被提升,但函式內容並不會。

    function example() {
      console.log(anonymous); // => undefined
    
      anonymous(); // => TypeError anonymous is not a function
    
      var anonymous = function() {
        console.log('anonymous function expression');
      };
    }
  • 14.3 賦予命名函式的變數會被提升,但函式內容及函式名稱並不會。

    function example() {
      console.log(named); // => undefined
    
      named(); // => TypeError named is not a function
    
      superPower(); // => ReferenceError superPower is not defined
    
      var named = function superPower() {
        console.log('Flying');
      };
    }
    
    // 當函式名稱和變數名稱相同時也是如此。
    function example() {
      console.log(named); // => undefined
    
      named(); // => TypeError named is not a function
    
      var named = function named() {
        console.log('named');
      }
    }
  • 14.4 宣告函式的名稱及函式內容都會被提升。

    function example() {
      superPower(); // => Flying
    
      function superPower() {
        console.log('Flying');
      }
    }
  • 想瞭解更多訊息,請參考 JavaScript Scoping & Hoisting by Ben Cherry.

⬆ 回到頂端

條件式與等號

  • 15.1 請使用 ===!== ,別使用 ==!=

  • 15.2 像是 if 的條件語法內會使用 ToBoolean 的抽象方法強轉類型,並遵循以下規範:

    • 物件 轉換為 true
    • Undefined 轉換為 false
    • Null 轉換為 false
    • 布林 轉換為 該布林值
    • 數字 如果是 +0, -0, 或 NaN 則轉換為 false,其他的皆為 true
    • 字串 如果是空字串 '' 則轉換為 false ,其他的皆為 true
    if ([0]) {
      // true
      // 陣列為一個物件,所以轉換為 true
    }
  • 15.3 使用簡短的方式。

    // bad
    if (name !== '') {
      // ...stuff...
    }
    
    // good
    if (name) {
      // ...stuff...
    }
    
    // bad
    if (collection.length > 0) {
      // ...stuff...
    }
    
    // good
    if (collection.length) {
      // ...stuff...
    }
  • 15.4 想瞭解更多訊息請參考 Angus Croll 的 Truth Equality and JavaScript

⬆ 回到頂端

區塊

  • 16.1 多行區塊請使用花括號刮起來。

    // bad
    if (test)
      return false;
    
    // good
    if (test) return false;
    
    // good
    if (test) {
      return false;
    }
    
    // bad
    function() { return false; }
    
    // good
    function() {
      return false;
    }
  • 16.2 如果你使用 ifelse 的多行區塊,請將 else 放在 if 區塊的結尾花括號下。

    // bad
    if (test) {
      thing1();
      thing2();
    }
    else {
      thing3();
    }
    
    // good
    if (test) {
      thing1();
      thing2();
    } else {
      thing3();
    }

⬆ 回到頂端

註解

  • 17.1 多行註解請使用 /** ... */ ,包含描述,指定類型以及參數值還有回傳值。

    // bad
    // make() 根據傳入的 tag 名稱回傳一個新的元件
    //
    // @param {String} tag
    // @return {Element} element
    function make(tag) {
    
      // ...stuff...
    
      return element;
    }
    
    // good
    /**
     * make() 根據傳入的 tag 名稱回傳一個新的元件
     *
     * @param {String} tag
     * @return {Element} element
     */
    function make(tag) {
    
      // ...stuff...
    
      return element;
    }
  • 17.2 單行註解請使用 // ,在欲註解的地方上方進行當行註解,並在註解前空一格。

    // bad
    const active = true;  // 當目前分頁
    
    // good
    // is current tab
    const active = true;
    
    // bad
    function getType() {
      console.log('fetching type...');
      // 設定預設的類型為 'no type'
      const type = this._type || 'no type';
    
      return type;
    }
    
    // good
    function getType() {
      console.log('fetching type...');
    
      // 設定預設的類型為 'no type'
      const type = this._type || 'no type';
    
      return type;
    }
  • 17.3 在註解前方加上 FIXMETODO 可以幫助其他開發人員快速瞭解這是一個需要重新討論的問題,或是一個等待解決的問題。和一般的註解不同,他們是可被執行的。對應的動作為 FIXME -- 重新討論並解決TODO -- 必須執行

  • 17.4 使用 // FIXME: 標注問題。

    class Calculator extends Abacus {
      constructor() {
        super();
    
        // FIXME: 不該在這使用全域變數
        total = 0;
      }
    }
  • 17.5 使用 // TODO: 標注問題的解決方式。

    class Calculator extends Abacus {
      constructor() {
        super();
    
        // TODO: total 應該可被傳入的參數所修改
        this.total = 0;
      }
    }

⬆ 回到頂端

空格

  • 18.1 將 Tab 設定為兩個空格。

    // bad
    function() {
    ∙∙∙∙const name;
    }
    
    // bad
    function() {
    ∙const name;
    }
    
    // good
    function() {
    ∙∙const name;
    }
  • 18.2 在花括號前加一個空格。

    // bad
    function test(){
      console.log('test');
    }
    
    // good
    function test() {
      console.log('test');
    }
    
    // bad
    dog.set('attr',{
      age: '1 year',
      breed: 'Bernese Mountain Dog',
    });
    
    // good
    dog.set('attr', {
      age: '1 year',
      breed: 'Bernese Mountain Dog',
    });
  • 18.3 在控制流程的語句(if, while 等等。)的左括號前加上一個空格。宣告的函式和傳入的變數間則沒有空格。

    // bad
    if(isJedi) {
      fight ();
    }
    
    // good
    if (isJedi) {
      fight();
    }
    
    // bad
    function fight () {
      console.log ('Swooosh!');
    }
    
    // good
    function fight() {
      console.log('Swooosh!');
    }
  • 18.4 將運算元用空格隔開。

    // bad
    const x=y+5;
    
    // good
    const x = y + 5;
  • 18.5 在檔案的最尾端加上一行空白行。

    // bad
    (function(global) {
      // ...stuff...
    })(this);
    // bad
    (function(global) {
      // ...stuff...
    })(this);
    
    // good
    (function(global) {
      // ...stuff...
    })(this);
  • 18.6 當多個方法連接時請換行縮排,利用前面的 . 強調該行是呼叫方法,而不是一個新的宣告。

    // bad
    $('#items').find('.selected').highlight().end().find('.open').updateCount();
    
    // bad
    $('#items').
      find('.selected').
        highlight().
        end().
      find('.open').
        updateCount();
    
    // good
    $('#items')
      .find('.selected')
        .highlight()
        .end()
      .find('.open')
        .updateCount();
    
    // bad
    const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').class('led', true)
        .attr('width', (radius + margin) * 2).append('svg:g')
        .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
        .call(tron.led);
    
    // good
    const leds = stage.selectAll('.led')
        .data(data)
      .enter().append('svg:svg')
        .classed('led', true)
        .attr('width', (radius + margin) * 2)
      .append('svg:g')
        .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
        .call(tron.led);
  • 18.7 在區塊的結束及下個語法間加上空行。

    // bad
    if (foo) {
      return bar;
    }
    return baz;
    
    // good
    if (foo) {
      return bar;
    }
    
    return baz;
    
    // bad
    const obj = {
      foo() {
      },
      bar() {
      },
    };
    return obj;
    
    // good
    const obj = {
      foo() {
      },
    
      bar() {
      },
    };
    
    return obj;
    
    // bad
    const arr = [
      function foo() {
      },
      function bar() {
      },
    ];
    return arr;
    
    // good
    const arr = [
      function foo() {
      },
    
      function bar() {
      },
    ];
    
    return arr;

⬆ 回到頂端

逗號

  • 19.1 不要將逗號放在前方。

    // bad
    const story = [
        once
      , upon
      , aTime
    ];
    
    // good
    const story = [
      once,
      upon,
      aTime,
    ];
    
    // bad
    const hero = {
        firstName: 'Ada'
      , lastName: 'Lovelace'
      , birthYear: 1815
      , superPower: 'computers'
    };
    
    // good
    const hero = {
      firstName: 'Ada',
      lastName: 'Lovelace',
      birthYear: 1815,
      superPower: 'computers',
    };
  • 19.2 增加結尾的逗號:別懷疑

為什麼?這會讓 Git 的差異列表更乾淨。另外,Babel 轉譯器也會刪除結尾多餘的逗號,也就是說你完全不需要擔心在老舊的瀏覽器發生多餘逗號的問題

```javascript
// bad - 不含多餘逗號的 git 差異列表
const hero = {
     firstName: 'Florence',
-    lastName: 'Nightingale'
+    lastName: 'Nightingale',
+    inventorOf: ['coxcomb graph', 'modern nursing']
}

// good - 包含多餘逗號的 git 差異列表
const hero = {
     firstName: 'Florence',
     lastName: 'Nightingale',
+    inventorOf: ['coxcomb chart', 'modern nursing'],
}

// bad
const hero = {
  firstName: 'Dana',
  lastName: 'Scully'
};

const heroes = [
  'Batman',
  'Superman'
];

// good
const hero = {
  firstName: 'Dana',
  lastName: 'Scully',
};

const heroes = [
  'Batman',
  'Superman',
];
```

⬆ 回到頂端

分號

  • 20.1 對啦。

    // bad
    (function() {
      const name = 'Skywalker'
      return name
    })()
    
    // good
    (() => {
      const name = 'Skywalker';
      return name;
    })();
    
    // good(防止當兩個檔案含有立即函式需要合併時,函式被當成參數處理)
    ;(() => {
      const name = 'Skywalker';
      return name;
    })();

    瞭解更多.

⬆ 回到頂端

型別轉換

  • 21.1 在開頭的宣告進行強制型別轉換。

  • 21.2 字串:

    //  => this.reviewScore = 9;
    
    // bad
    const totalScore = this.reviewScore + '';
    
    // good
    const totalScore = String(this.reviewScore);
  • 21.3 對數字使用 parseInt 轉換,並帶上型別轉換的基數。

    const inputValue = '4';
    
    // bad
    const val = new Number(inputValue);
    
    // bad
    const val = +inputValue;
    
    // bad
    const val = inputValue >> 0;
    
    // bad
    const val = parseInt(inputValue);
    
    // good
    const val = Number(inputValue);
    
    // good
    const val = parseInt(inputValue, 10);
  • 21.4 如果你因為某個原因在做些瘋狂的事情,但是 parseInt 是你的瓶頸,所以你對於性能方面的原因而必須使用位元右移,請留下評論並解釋為什麼使用,及你做了哪些事情。

    // good
    /**
     * 使用 parseInt 導致我的程式變慢,改成使用
     * 位元右移強制將字串轉為數字加快了他的速度。
     */
    const val = inputValue >> 0;
  • 21.5 **注意:**使用位元轉換時請小心,數字為 64 位元數值,但是使用位元轉換時則會回傳一個 32 位元的整數(來源),這會導致大於 32 位元的數值產生異常 討論串,32 位元的整數最大值為 2,147,483,647:

    2147483647 >> 0 //=> 2147483647
    2147483648 >> 0 //=> -2147483648
    2147483649 >> 0 //=> -2147483647
  • 21.6 布林:

    const age = 0;
    
    // bad
    const hasAge = new Boolean(age);
    
    // good
    const hasAge = Boolean(age);
    
    // good
    const hasAge = !!age;

⬆ 回到頂端

命名規則

  • 22.1 避免使用單一字母的名稱,讓你的名稱有解釋的含義。

    // bad
    function q() {
      // ...stuff...
    }
    
    // good
    function query() {
      // ..stuff..
    }
  • 22.2 使用駝峰式大小寫命名物件,函式及實例。

    // bad
    const OBJEcttsssss = {};
    const this_is_my_object = {};
    function c() {}
    
    // good
    const thisIsMyObject = {};
    function thisIsMyFunction() {}
  • 22.3 使用帕斯卡命名法來命名建構子或類別。

    // bad
    function user(options) {
      this.name = options.name;
    }
    
    const bad = new user({
      name: 'nope',
    });
    
    // good
    class User {
      constructor(options) {
        this.name = options.name;
      }
    }
    
    const good = new User({
      name: 'yup',
    });
  • 22.4 命名私有屬性時請在前面加底線 _

    // bad
    this.__firstName__ = 'Panda';
    this.firstName_ = 'Panda';
    
    // good
    this._firstName = 'Panda';
  • 22.5 請別儲存 this 為參考。請使用箭頭函式或是 Function#bind。

    // bad
    function foo() {
      const self = this;
      return function() {
        console.log(self);
      };
    }
    
    // bad
    function foo() {
      const that = this;
      return function() {
        console.log(that);
      };
    }
    
    // good
    function foo() {
      return () => {
        console.log(this);
      };
    }
  • 22.6 如果你的檔案只有輸出一個類別,你的檔案名稱必須和你的類別名稱相同。

    // 檔案內容
    class CheckBox {
      // ...
    }
    export default CheckBox;
    
    // 在其他的檔案
    // bad
    import CheckBox from './checkBox';
    
    // bad
    import CheckBox from './check_box';
    
    // good
    import CheckBox from './CheckBox';
  • 22.7 當你導出為預設的函式時請使用駝峰式大小寫。檔案名稱必須與你的函式名稱一致。

    function makeStyleGuide() {
    }
    
    export default makeStyleGuide;
  • 22.8 當你導出為單例 / 函式庫 / 空物件時請使用帕斯卡命名法。

    const AirbnbStyleGuide = {
      es6: {
      }
    };
    
    export default AirbnbStyleGuide;

⬆ 回到頂端

存取器

  • 23.1 存取器不是必須的。

  • 23.2 如果你要建立一個存取器,請使用 getVal() 及 setVal('hello')。

    // bad
    dragon.age();
    
    // good
    dragon.getAge();
    
    // bad
    dragon.age(25);
    
    // good
    dragon.setAge(25);
  • 23.3 如果屬性是布林,請使用 isVal()hasVal()

    // bad
    if (!dragon.age()) {
      return false;
    }
    
    // good
    if (!dragon.hasAge()) {
      return false;
    }
  • 23.4 可以建立 get() 及 set() 函式,但請保持一致。

    class Jedi {
      constructor(options = {}) {
        const lightsaber = options.lightsaber || 'blue';
        this.set('lightsaber', lightsaber);
      }
    
      set(key, val) {
        this[key] = val;
      }
    
      get(key) {
        return this[key];
      }
    }

⬆ 回到頂端

事件

  • 24.1 當需要對事件傳入資料時(不論是 DOM 事件或是其他私有事件),請傳入物件替代單一的資料。這樣可以使之後的開發人員直接加入其他的資料到事件裡,而不需更新該事件的處理器。例如,比較不好的做法:

    // bad
    $(this).trigger('listingUpdated', listing.id);
    
    ...
    
    $(this).on('listingUpdated', function(e, listingId) {
      // do something with listingId
    });

    更好的做法:

    // good
    $(this).trigger('listingUpdated', { listingId: listing.id });
    
    ...
    
    $(this).on('listingUpdated', function(e, data) {
      // do something with data.listingId
    });

⬆ 回到頂端

jQuery

  • 25.1 jQuery 的物件請使用 $ 當前綴。

    // bad
    const sidebar = $('.sidebar');
    
    // good
    const $sidebar = $('.sidebar');
    
    // good
    const $sidebarBtn = $('.sidebar-btn');
  • 25.2 快取 jQuery 的查詢。

    // bad
    function setSidebar() {
      $('.sidebar').hide();
    
      // ...stuff...
    
      $('.sidebar').css({
        'background-color': 'pink'
      });
    }
    
    // good
    function setSidebar() {
      const $sidebar = $('.sidebar');
      $sidebar.hide();
    
      // ...stuff...
    
      $sidebar.css({
        'background-color': 'pink'
      });
    }
  • 25.3 DOM 的查詢請使用層遞的 $('.sidebar ul') 或 父元素 > 子元素 $('.sidebar > ul')jsPerf

  • 25.4 對作用域內的 jQuery 物件使用 find 做查詢。

    // bad
    $('ul', '.sidebar').hide();
    
    // bad
    $('.sidebar').find('ul').hide();
    
    // good
    $('.sidebar ul').hide();
    
    // good
    $('.sidebar > ul').hide();
    
    // good
    $sidebar.find('ul').hide();

⬆ 回到頂端

ECMAScript 5 相容性

⬆ 回到頂端

ECMAScript 6 風格

  • 27.1 以下是連結到各個 ES6 特性的列表。
  1. 箭頭函式
  2. 類別
  3. 物件簡寫
  4. 簡潔物件
  5. 可計算的物件屬性
  6. 模板字串
  7. 解構子
  8. 預設參數
  9. 剩餘參數(Rest)
  10. 陣列擴展
  11. Let 及 Const
  12. 迭代器及產生器
  13. 模組

⬆ 回到頂端

測試

  • 28.1 如題。

    function() {
      return true;
    }

⬆ 回到頂端

效能

⬆ 回到頂端

資源

學習 ES6

請讀這個

工具

其他的風格指南

其他風格

瞭解更多

書籍

部落格

Podcasts

⬆ 回到頂端

誰在使用

這是正在使用這份風格指南的組織列表。送一個 pull request 或提一個 issue 讓我們將你增加到列表上。

⬆ 回到頂端

翻譯

This style guide is also available in other languages:

JavaScript 風格指南

與我們討論 JavaScript

貢獻者

License

(The MIT License)

Copyright (c) 2014 Airbnb

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

⬆ 回到頂端

Amendments

We encourage you to fork this guide and change the rules to fit your team's style guide. Below, you may list some amendments to the style guide. This allows you to periodically update your style guide without having to deal with merge conflicts.

};

About

Airbnb JavaScript Style Guide 正體中文版

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%