天天看點

初學ES6筆記二十二程式設計風格

本人的筆記内容來自于[阮一峰老師的ECMAScript 6 詳細内容請看(http://es6.ruanyifeng.com/#docs/array)

程式設計風格

一、塊級作用域

(1)let 取代 var

let和const ,let完全可以取代var,因為兩者語義相同,而且let沒有副作用。

'use strict';

if (true) {
  let x = 'hello';
}

for (let i = 0; i < 10; i++) {
  console.log(i);
}
           

var指令存在變量提升效用

,let指令沒有這個問題。

'use strict';

if (true) {
  console.log(x); // ReferenceError
  let x = 'hello';
}
           

如果使用var替代let,console.log那一行就不會報錯,而是會輸出undefined,因為變量聲明提升到代碼塊的頭部。這違反了變量先聲明後使用的原則。

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

在let和const之間,建議優先使用const,尤其

是在全局環境,不應該設定變量,隻應設定常量

const優于let有幾個原因。

一個是const可以提醒閱讀程式的人,這個

變量不應該改變

另一個是const比較符合函數式程式設計思想,

運算不改變值,隻是建立值

,而且這樣也有利于将來的分布式運算;

最後一個原因是

JavaScript 編譯器會對const進行優化

,是以多使用const,有利于提高程式的運作效率,也就是說let和const的本質差別,其實是編譯器内部的處理不同。

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

const聲明常量還有兩個好處,

一是閱讀代碼的人立刻會

意識到不應該修改這個值

二是

防止了無意間修改

變量值所導緻的錯誤。

所有的函數都應該設定為常量。

二、字元串

靜态字元串一律使用單引号或反引号

,不使用雙引号。

動态字元串使用反引号

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

// acceptable
const c = `foobar`;

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

三、解構指派

使用數組成員對變量指派時,

優先使用解構指派

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

四、對象

單行定義的對象,最後一個成員不以逗号結尾

多行定義

的對象,最後一個成員以

逗号結尾。

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

如果對象的屬性名是動态的,可以在創造對象的時候,使用屬性表達式定義。

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

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

對象obj的最後一個屬性名,需要計算得到。這時最好采用屬性表達式,在建立obj的時候,将該屬性與其他屬性定義在一起。這樣一來,所有屬性就在一個地方定義了。

對象的屬性和方法,盡量采用簡潔表達法,

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

五、數組

使用

擴充運算符(...)拷貝數組

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

六、函數

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

(() => {
  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);
           

箭頭函數取代Function.prototype.bind,不應再用 self/_this/that 綁定 this。

// bad
const self = this;
const boundMethod = function(...params) {
  return method.apply(self, params);
}

// acceptable
const boundMethod = method.bind(this);

// best
const boundMethod = (...params) => method.apply(this, params);
           

所有配置項都應該集中在一個對象,放在最後一個參數,布爾值不可以直接作為參數。

// bad
function divide(a, b, option = false ) {
}

// good
function divide(a, b, { option = false } = {}) {
}
           

不要在函數體内使用 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 = {}) {
  // ...
}
           

七、Map 結構

注意區分 Object 和 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]);
}
           

八、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運算的危險。

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

九、子產品

首先,Module 文法是 JavaScript 子產品的标準寫法,堅持使用這種寫法。使用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';

class Breadcrumbs extends React.Component {
  render() {
    return <nav />;
  }
};

export default Breadcrumbs;
           

如果子產品隻有一個輸出值,就使用export default

,如果

子產品有多個輸出值,就不使用export default,export default與普通的export不要同時使用

不要在子產品輸入中使用通配符

。因為這樣可以確定你的子產品之中,有一個預設輸出(export default)。

// bad
import * as myObject from './importModule';

// good
import myObject from './importModule';
           

如果子產品預設輸出一個函數,函數名的首字母應該小寫。

function makeStyleGuide() {
}

export default makeStyleGuide;
           

如果子產品預設輸出一個對象,對象名的首字母應該大寫。

const StyleGuide = {
  es6: {
  }
};

export default StyleGuide;
           

十、ESLint 的使用

ESLint 是一個文法規則和代碼風格的檢查工具

,可以用來保證寫出文法正确、風格統一的代碼。

首先,安裝 ESLint。

$ npm i -g eslint
           

然後,安裝 Airbnb 文法規則,以及 import、a11y、react 插件。

$ npm i -g eslint-config-airbnb
$ npm i -g eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react
           

最後,在項目的根目錄下建立一個.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:1  error  Unexpected var, use let or const instead          no-var
  1:5  error  unusued is defined but never used                 no-unused-vars
  4:5  error  Expected indentation of 2 characters but found 4  indent
  4:5  error  Unexpected var, use let or const instead          no-var
  5:5  error  Expected indentation of 2 characters but found 4  indent

✖ 5 problems (5 errors, 0 warnings)
           

原檔案有五個錯誤,其中兩個是不應該使用var指令,而要使用let或const;一個是定義了變量,卻沒有使用;另外兩個是行首縮進為 4 個空格,而不是規定的 2 個空格。