JS的編碼風格

來自Airbnb JavaScript Style Guide的學習:

1.命名應具備描述性

// bad
function a(){
    alert('hello');
}

// good
function sayHello(){
    alert('hello');
}

2.使用駝峯式命名對象、函數和實例

// bad
var OBJEcttsssss = {};
var this_is_my_object = {};
var o = {};
function c() {}

// good
var thisIsMyObject = {};
function thisIsMyFunction() {}

3.使用帕斯卡式命名(大駝峯命名)構造函數或類

// bad
function user(options) {
  this.name = options.name;
}

var bad = new user({
  name: 'nope'
});

// good
function User(options) {
  this.name = options.name;
}

var good = new User({
  name: 'yup'
});

4.不要使用下劃線前/後綴(因爲JavaScript 並沒有私有屬性或私有方法的概念。雖然使用下劃線是表示「私有」的一種共識,但實際上這些屬性是完全公開的,它本身就是你公共接口的一部分。這種習慣或許會導致開發者錯誤的認爲改動它不會造成破壞或者不需要去測試。長話短說:如果你想要某處爲「私有」,它必須不能是顯式提出的。)

//bad
this.__firstName__ = 'Jack';
this.__firstName = 'Jack';
this._firstName = 'Jack';
this.firstName_ = 'Jack';

//good
this.firstName = 'Jack';

5.不要保存 this 的引用。使用 Function#bind

// bad
function () {
  var self = this;
  return function () {
    console.log(self);
  };
}
// bad
function () {
  var that = this;
  return function () {
    console.log(that);
  };
}
// bad
function () {
  var _this = this;
  return function () {
    console.log(_this);
  };
}

// good
function () {
  return function () {
    console.log(this);
  }.bind(this);
}

6.給函數命名。這在做堆棧軌跡時很有幫助(不過IE8 及以下版本對命名函數表達式的處理有些怪異。)

// bad
var log = function (msg) {
  console.log(msg);
};

// good
var log = function log(msg) {
  console.log(msg);
};

7.如果你的文件導出一個類,你的文件名應該與類名完全相同。

// file contents
class CheckBox {
// ...
}
module.exports = CheckBox;

// in some other file
// bad
var CheckBox = require('./checkBox');

// bad
var CheckBox = require('./check_box');

// good
var CheckBox = require('./CheckBox');

 8.1存取器(屬性的存取函數不是必須的)

如果你需要存取函數時使用 getVal()setVal('hello')

// bad
dragon.age();

// good
dragon.getAge();

// bad
dragon.age(25);

// good
dragon.setAge(25);

8.2如果屬性是布爾值,使用 isVal()hasVal()

// bad
if (!dragon.age()) {
  return false;
}

// good
if (!dragon.hasAge()) {
  return false;
}

8.3創建 get() 和 set() 函數是可以的,但要保持一致。

function Jedi(options) {
  options || (options = {});
  var lightsaber = options.lightsaber || 'blue';
  this.set('lightsaber', lightsaber);
}

Jedi.prototype.set = function set(key, val) {
  this[key] = val;
};

Jedi.prototype.get = function get(key) {
  return this[key];
};

9.1使用 $ 作爲存儲 jQuery 對象的變量名前綴。

//bad
var content = $('#content');
//good
var $content = $('#content');

9.2緩存Jquery查詢

//bad
function setSidebar() {
  $('.sidebar').hide();

  // ...stuff...

  $('.sidebar').css({
    'background-color': 'pink'
  });
} 

//good
function setSidebar() {
  var $sidebar = $('.sidebar');

  $sidebar.hide();
  // ...stuff...

  $sidebar.css({
    'background-color': 'pink'
  });
}

9.3對 DOM 查詢使用層疊 $('.sidebar ul') 或 父元素 > 子元素 $('.sidebar > ul')

9.4對有作用域的 jQuery 對象查詢使用 find

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

// good
$('.sidebar ul').hide();

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

// good
var $sidebar = $('.sidebar');
$sidebar.find('ul').hide();

10.1使用直接量創建數組

// bad
var items = new Array();

// good
var items = [];

10.2向數組增加元素時使用 Array#push 來替代直接賦值

var someStack = []; //console.log(someStack.length); // 0

// bad
someStack[someStack.length] = 'Jack';

// good
someStack.push('Jack');

10.3當你需要拷貝數組時,使用 Array#slice

var len = items.length;
var itemsCopy = [];
var i;

// bad
for (i = 0; i < len; i++) {
  itemsCopy[i] = items[i];
}

// good
itemsCopy = items.slice();

11.1使用單引號 '' 包裹字符串

// bad
var name = "Jack";
// bad
var introduce = "My name is " + name;
// good
var name = 'Jack';
// good
var introduce = 'My name is ' + name;

11.2超過 100 個字符的字符串應該使用連接符寫成多行(注:若過度使用,通過連接符連接的長字符串可能會影響性能)

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

11.3程序化生成的字符串使用 Array#join 連接而不是使用連接符。尤其是 IE 下

var items;
var messages;
var length;
var 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++) {
    // use direct assignment in this case because we're micro-optimizing.(最佳化)
    items[i] = '<li>' + messages[i].message + '</li>';
  }

  return '<ul>' + items.join('') + '</ul>';
}

12.1總是使用 var 來聲明變量。不這麼做將導致產生全局變量。我們要避免污染全局命名空間(比如:var num = 1;

是在當前域中聲明變量. 如果在方法中聲明,則爲局部變量(local variable);如果是在全局域中聲明,則爲全局變量。

而 num = 1;事實上是對屬性賦值操作。首先,它會嘗試在當前作用域鏈(如在方法中聲明,則當前作用域鏈代表全局作用域和方法局部作用域etc。。。)中解析 num; 如果在任何當前作用域鏈中找到num,則會執行對num屬性賦值; 如果沒有找到num,它纔會在全局對象(即當前作用域鏈的最頂層對象,如window對象)中創造num屬性並賦值。

注意!它並不是聲明瞭一個全局變量,而是創建了一個全局對象的屬性。

var num = 1 跟 num = 1,前者是變量聲明,帶不可刪除屬性,因此無法被刪除;後者爲全局變量的一個屬性,因此可以從全局變量中刪除。)

// bad
superPower = new SuperPower();

// good
var superPower = new SuperPower();

12.2使用 var 聲明每一個變量。 這樣做的好處是增加新變量將變的更加容易,而且你永遠不用再擔心調換錯 ;,

// bad
var items = getItems(),
    goSportsTeam = true,
    dragonball = 'z';

// bad
// (跟上面的代碼比較一下,看看哪裏錯了)
var items = getItems(),
    goSportsTeam = true;
    dragonball = 'z';

// good
var items = getItems();
var goSportsTeam = true;
var dragonball = 'z';

12.3最後再聲明未賦值的變量。當你需要引用前面的變量賦值時這將變的很有用

// bad
var i, len, dragonball,
    items = getItems(),
    goSportsTeam = true;

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

// good
var items = getItems();
var goSportsTeam = true;
var dragonball;
var length;
var i;

 13.比較運算符&等號

 13.1優先使用 ===!== 而不是 ==!=.

 13.2條件表達式例如 if 語句通過抽象方法 ToBoolean 強制計算它們的表達式並且總是遵守下面的規則:

1.對象 被計算爲 true
2.Undefined 被計算爲 false
3.Null 被計算爲 false
4.布爾值 被計算爲 布爾的值
5.數字 如果是 +0、-0 或 NaN 被計算爲 false,否則爲 true
6.字符串 如果是空字符串 '' 被計算爲 false,否則爲 true

if ([0]) {
  // true
  // 一個數組就是一個對象,對象被計算爲 true
}

var c;
if(c){
  // false
  // Undefined 被計算爲false
}

//快捷方式
// bad
if (name !== '') {
  // ...stuff...
}

// good
if (name) {
  // ...stuff...
}

// bad
if (collection.length > 0) {
  // ...stuff...
}

// good
if (collection.length) {
  // ...stuff...
}

14.1使用兩個空格作爲縮進

// bad
function () {
∙∙∙∙var name;
}

// bad
function () {
∙var name;
}

// good
function () {
∙∙var name;
}

14.1在大括號前放一個空格

// 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'
});

14.2在控制語句(ifwhile 等)的小括號前放一個空格。在函數調用及聲明中,不在函數的參數列表前加空格。

// bad
if(isJedi) {
  fight ();
}

// good
if (isJedi) {
  fight();
}

// bad
function fight () {
  console.log ('Swooosh!');
}

// good
function fight() {
  console.log('Swooosh!');
}

14.3使用空格把運算符隔開。

// bad
var sum=x+y;
// good
var sum = x + y;

15.1類型轉換布爾

ar age = 0;

// bad
var hasAge = new Boolean(age);

// good
var hasAge = Boolean(age);

// good
var hasAge = !!age;

 

15.2使用 parseInt 轉換數字時總是帶上類型轉換的基數。

var inputValue = '4';

// bad
var val = new Number(inputValue);

// bad
var val = +inputValue;

// bad
var val = inputValue >> 0;

// bad
var val = parseInt(inputValue);

// good
var val = Number(inputValue);

// good
var val = parseInt(inputValue, 10);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章