ES6中也要使用好嚴格的代碼規範,助力你寫出優雅的代碼

經常使用約定

啓用eslint

必需開啓eslint檢測, 且使用 standard規範檢測,這樣你們寫出來的代碼風格就能夠保持一致git

語法

類型規範

  • 對於常量或不修改的變量聲明使用const,對於只在當前做用域下有效的變量,應使用let,再也不使用var;
  • 優先使用const;
  • 將全部 const 變量放在一塊兒,而後將全部 let 變量放在一塊兒。
const foo = 2222

let foo1 = 222222
let bar = foo
bar = 93333
foo1 = 33333
複製代碼
直接存取基本類型
  • 字符串
  • 數值
  • 布爾類型
  • null
  • undefined
const foo = 1222;

let bar = foo;

bar = 9222222;

console.log(foo, bar);
複製代碼
經過引用的方式存取複雜類型,對全部的引用使用 const
  • 對象
  • 數組
  • 函數
const foo = [1, 2, 3, 10];

const bar = foo;

bar[0] = 90000;

複製代碼
優先使用模板字符串,靜態字符串一概使用單引號或反引號,不建議使用雙引號。
//bad
 const a = "foobar";
 const b = 'foo'+a+'bb';

// good
const a = 'foobar';
const b = `foo${a}bar`;
複製代碼
使用字面量語法建立數組
// bad
const items = new Array();

// good
const items = [];
複製代碼
使用字面值建立對象
// bad

const item = new Object();

// good

const item = {};
複製代碼

解構規範

優先使用解構賦值
const arr = [1, 2, 3, 4, 10];

// bad
const first = arr[0];
const second = arr[1];

// good
const [first, second] = arr;



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

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

// best
function getFullName({ firstName, lastName }) {
}



//若是函數返回多個值,優先使用對象的解構賦值,而不是數組的解構賦值。這樣便於之後添加返回值,以及更改返回值的順序。

// bad
function processInput(input) {
  return [left, right, top, bottom];
}

// good
function processInput(input) {
  return { left, right, top, bottom };
}

const { left, right } = processInput(input);
複製代碼
解構語句中統一不使用圓括號
// bad
[(a)] = [11]; // a未定義
let { a: (b) } = {}; // 解析出錯


// good
let [a, b] = [11, 22];
複製代碼
使用對象屬性值的簡寫
const aSkywalker = 'a Skywalker';

// bad

const obj = {

    aSkywalker: aSkywalker,

};

// good

const obj = {

    aSkywalker,

};
複製代碼
在對象屬性聲明前把簡寫的屬性分組
const a = 'Anakin Skywalker';

const b = 'a Skywalker';

// bad

const obj = {

    a: 1,

    b: 2,

    c: 3,

    d: 3,

    e: 4,

    z: 10,

};

// good

const obj = {

    a,

    b,

    c,

    d,

    e,

    f

};
複製代碼

函數

使用函數聲明而不是函數表達式

函數聲明擁有函數名,在調用棧中更加容易識別。而且,函數聲明會總體提高,而函數表達式只會提高變量自己。這條規則也能夠這樣描述,始終使用箭頭函數來代替函數表達式。es6

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

// good
function foo() {
}
複製代碼

絕對不要在一個非函數塊(if,while,等等)裏聲明一個函數,把那個函數賦給一個變量。瀏覽器容許你這麼作,可是它們解析不一樣注:ECMA-262 把 塊 定義爲一組語句,函數聲明不是一個語句。閱讀 ECMA-262 對這個問題的說明github

// bad
if (currentUser) {
  function test() {
    console.log('Nope.');
  }
}

// good
if (currentUser) {
  var test = function test() {
    console.log('Yup.');
  };
}
複製代碼

絕對不要把參數命名爲 arguments, 這將會覆蓋函數做用域內傳過來的 arguments 對象數組

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

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

複製代碼
不要使用 arguments。能夠選擇 rest 語法 ... 替代。

使用 ... 能明確你要傳入的參數。另外 rest 參數是一個真正的數組,而 arguments 是一個類數組。瀏覽器

// bad

function concatenateAll() {

    const args = Array.prototype.slice.call(arguments);

    return args.join('');

}

// good

function concatenateAll(...args) {

    return args.join('');

}
複製代碼
使用函數參數默認值語法,而不是修改函數的實參
// really bad
function handleThings(opts) {
  opts = opts || {};
}

// still bad
function handleThings(opts) {
  if (opts === void 0) {
    opts = {};
  }
}

// good
function handleThings(opts = {}) {
  // ...
}
複製代碼
箭頭函數

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

// bad

[1, 2, 3].map(function (x) {

    return x * x;

});

// good

[1, 2, 3].map((x) => {

    return x * x;

});
複製代碼

若是一個函數適合用一行寫出而且只有一個參數,那就把花括號、圓括號和 return 都省略掉。若是不是,那就不要省略。app

// good

[1, 2, 3].map(x => x * x);

// good

[1, 2, 3].reduce((total, n) => {

    return total + n;

}, 0);

複製代碼

老是使用 class 關鍵字,避免直接修改 prototype,class 語法更簡潔,也更易理解。ide

// 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;
  }
}
複製代碼

定義類時,方法的順序以下:函數

  • constructor
  • public get/set 公用訪問器,set只能傳一個參數
  • public methods 公用方法,公用相關命名使用小駝峯式寫法(lowerCamelCase)
  • private get/set 私有訪問器,私有相關命名應加上下劃線 _ 爲前綴
  • private methods 私有方法
// good
class SomeClass {
  constructor() {
    // constructor
  }

  get aval() {
    // public getter
  }

  set aval(val) {
    // public setter
  }

  doSth() {
    // 公用方法
  }

  get _aval() {
    // private getter
  }

  set _aval() {
    // private setter
  }

  _doSth() {
    // 私有方法
  }
}
複製代碼

若是不是class類,不使用newui

// not good
function Foo() {

}
const foo = new Foo();

// good
class Foo {

}
const foo = new Foo();
複製代碼

使用 extends 關鍵字來繼承

這是一個內置的繼承方式,而且不會破壞 instanceof 原型檢查。

// 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];
    }
  }
複製代碼

模塊

老是在非標準的模塊系統中使用標準的 import 和 export 語法,咱們老是能夠將標準的模塊語法轉換成支持特定模塊加載器的語法。

推薦使用import和export來作模塊加載

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

複製代碼

不要使用通配符 * 的 import,這樣確保了一個模塊只有一個默認的 export 項

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

// good
import AirbnbStyleGuide from './AirbnbStyleGuide';
複製代碼

不要直接從一個 import 上 export

雖然一行代碼看起來更簡潔,可是有一個明確的 import 和一個明確的 export 使得代碼行爲更加明確。

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

// good
// filename es6.js
import { es6 } from './AirbnbStyleGuide';
export default es6;
複製代碼

多變量要導出時應採用對象解構形式

// not good
export const a= 'a';
export const b= 'b';

// good
export const a= 'a';
export const b= 'b';

export default { a, b };
複製代碼

導出單一一個類時,確保你的文件名就是你的類名

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

// in some other file
// bad
const checkB = require('./checkBox');

// bad
const checkB = require('./check_box');

// good
const checkB = require('./CheckB');
複製代碼

導出一個默認小駝峯命名的函數時,文件名應該就是導出的方法名

function makeGuid() {
}

export default makeGuid;
複製代碼

屬性訪問

使用點 . 操做符來訪問常量屬性

const a = {
  b: true,
  age: 28
};

// bad
const b = a['b'];

// good
const b = a.b;
複製代碼

使用中括號[] 操做符來訪問變量屬性

var a = {
  b: true,
  age: 28
};

function getProps(prop) {
  return a[prop];
}

var b = getProps('b');
複製代碼
相關文章
相關標籤/搜索