文章出處

編程風格

1. 塊級作用域

(1)let 取代 var

(2)全局常量和線程安全

 

  在letconst之間,建議優先使用const,尤其是在全局環境,不應該設置變量,只應設置常量。

  const優于let有幾個原因。

  一個是const可以提醒閱讀程序的人,這個變量不應該改變;

  另一個是const比較符合函數式編程思想,運算不改變值,只是新建值,而且這樣也有利于將來的分布式運算;

  最后一個原因是 JavaScript 編譯器會對const進行優化,所以多使用const,有利于提供程序的運行效率,也就是說letconst的本質區別,其實是編譯器內部的處理不同。

// bad
var a = 1, b = 2, c = 3;

// good
const a = 1;
const b = 2;
const c = 3;

// best
const [a, b, c] = [1, 2, 3];

 

2. 字符串

  靜態字符串一律使用單引號或反引號,不使用雙引號。動態字符串使用反引號。

// bad
const a = "foobar";
const b = 'foo' + a + 'bar';

// acceptable
const c = `foobar`;

// good
const a = 'foobar';
const b = `foo${a}bar`;
const c = 'foobar';

 

3. 解構賦值

  使用數組成員對變量賦值時,優先使用解構賦值。

const arr = [1, 2, 3, 4];

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

 

4. 對象

  單行定義的對象,最后一個成員不以逗號結尾。多行定義的對象,最后一個成員以逗號結尾。

// bad
const a = { k1: v1, k2: v2, };
const b = {
  k1: v1,
  k2: v2
};

// good
const a = { k1: v1, k2: v2 };
const b = {
  k1: v1,
  k2: v2,
};

 

  對象盡量靜態化,一旦定義,就不得隨意添加新的屬性。如果添加屬性不可避免,要使用Object.assign方法。

// bad
const a = {};
a.x = 3;

// if reshape unavoidable
const a = {};
Object.assign(a, { x: 3 });

// good
const a = { x: null };
a.x = 3;

 

  對象的屬性和方法,盡量采用簡潔表達法,這樣易于描述和書寫。

var ref = 'some value';

// bad
const atom = {
  ref: ref,

  value: 1,

  addValue: function (value) {
    return atom.value + value;
  },
};

// good
const atom = {
  ref,

  value: 1,

  addValue(value) {
    return atom.value + value;
  },
};

 

5. 數組

  使用擴展運算符(...)拷貝數組。

// bad
const len = items.length;
const itemsCopy = [];
let i;

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

// good
const itemsCopy = [...items];

 

  使用Array.from方法,將類似數組的對象轉為數組。

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

 

6. 函數

  立即執行函數可以寫成箭頭函數的形式。

(() => {
  console.log('Welcome to the Internet.');
})();

 

  那些需要使用函數表達式的場合,盡量用箭頭函數代替。因為這樣更簡潔,而且綁定了this。

// bad
[1, 2, 3].map(function (x) {
  return x * x;
});

// good
[1, 2, 3].map((x) => {
  return x * x;
});

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

 

  簡單的、單行的、不會復用的函數,建議采用箭頭函數。如果函數體較為復雜,行數較多,還是應該采用傳統的函數寫法。

  不要在函數體內使用arguments變量,使用rest運算符(...)代替。因為rest運算符顯式表明你想要獲取參數,而且arguments是一個類似數組的對象,而rest運算符可以提供一個真正的數組。

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

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

 

  使用默認值語法設置函數參數的默認值。

// bad
function handleThings(opts) {
  opts = opts || {};
}

// good
function handleThings(opts = {}) {
  // ...
}

 

7. Map結構 

  只有模擬現實世界的實體對象時,才使用Object。如果只是需要key: value的數據結構,使用Map結構。因為Map有內建的遍歷機制。

let map = new Map(arr);

for (let key of map.keys()) {
  console.log(key);
}

for (let value of map.values()) {
  console.log(value);
}

for (let item of map.entries()) {
  console.log(item[0], item[1]);
}

 

8. Class 

  總是用Class,取代需要prototype的操作。因為Class的寫法更簡潔,更易于理解。

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

 

  使用extends實現繼承,因為這樣更簡單,不會有破壞instanceof運算的危險。

9. 模塊

  使用import取代require

// bad
const moduleA = require('moduleA');
const func1 = moduleA.func1;
const func2 = moduleA.func2;

// good
import { func1, func2 } from 'moduleA';

 

  使用export取代module.exports

// commonJS的寫法
var React = require('react');

var Breadcrumbs = React.createClass({
  render() {
    return <nav />;
  }
});

module.exports = Breadcrumbs;

// ES6的寫法
import React from 'react';

const Breadcrumbs = React.createClass({
  render() {
    return <nav />;
  }
});

export default Breadcrumbs

 

  如果模塊只有一個輸出值,就使用export default,如果模塊有多個輸出值,就不使用export default,不要export default與普通的export同時使用。

  不要在模塊輸入中使用通配符。因為這樣可以確保你的模塊之中,有一個默認輸出(export default)。

  如果模塊默認輸出一個函數,函數名的首字母應該小寫。

  如果模塊默認輸出一個對象,對象名的首字母應該大寫。

const StyleGuide = {
  es6: {
  }
};

export default StyleGuide;

 

10. ESLint的使用

  ESLint是一個語法規則和代碼風格的檢查工具,可以用來保證寫出語法正確、風格統一的代碼。

  首先,安裝ESLint。

$ npm i -g eslint

 

  然后,安裝Airbnb語法規則。

$ npm i -g eslint-config-airbnb

 

  最后,在項目的根目錄下新建一個.eslintrc文件,配置ESLint。

{
  "extends": "eslint-config-airbnb"
}

 

  現在就可以檢查,當前項目的代碼是否符合預設的規則。

  index.js文件的代碼如下。

var unusued = 'I have no purpose!';

function greet() {
    var message = 'Hello, World!';
    alert(message);
}

greet();

 

  使用ESLint檢查這個文件。

$ eslint index.js
index.js
  1:5  error  unusued is defined but never used                 no-unused-vars
  4:5  error  Expected indentation of 2 characters but found 4  indent
  5:5  error  Expected indentation of 2 characters but found 4  indent

✖ 3 problems (3 errors, 0 warnings)

 

  上面代碼說明,原文件有三個錯誤,一個是定義了變量,卻沒有使用,另外兩個是行首縮進為4個空格,而不是規定的2個空格。

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()