ES6 編程風(fēng)格

2022-01-21 16:04 更新

1. 塊級(jí)作用域

(1)let 取代 var

ES6 提出了兩個(gè)新的聲明變量的命令:letconst 。其中,let 完全可以取代 var ,因?yàn)閮烧哒Z(yǔ)義相同,而且let沒(méi)有副作用。

'use strict';


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


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

上面代碼如果用 var 替代 let ,實(shí)際上就聲明了兩個(gè)全局變量,這顯然不是本意。變量應(yīng)該只在其聲明的代碼塊內(nèi)有效, var 命令做不到這一點(diǎn)。

var 命令存在變量提升效用, let 命令沒(méi)有這個(gè)問(wèn)題。

'use strict';


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

上面代碼如果使用 var 替代 let , console.log 那一行就不會(huì)報(bào)錯(cuò),而是會(huì)輸出 undefined ,因?yàn)樽兞柯暶魈嵘酱a塊的頭部。這違反了變量先聲明后使用的原則。

所以,建議不再使用 var 命令,而是使用 let 命令取代。

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

letconst之間,建議優(yōu)先使用const ,尤其是在全局環(huán)境,不應(yīng)該設(shè)置變量,只應(yīng)設(shè)置常量。

const 優(yōu)于 let 有幾個(gè)原因。一個(gè)是 const 可以提醒閱讀程序的人,這個(gè)變量不應(yīng)該改變;另一個(gè)是 const 比較符合函數(shù)式編程思想,運(yùn)算不改變值,只是新建值,而且這樣也有利于將來(lái)的分布式運(yùn)算;最后一個(gè)原因是 JavaScript 編譯器會(huì)對(duì) const 進(jìn)行優(yōu)化,所以多使用 const ,有利于提高程序的運(yùn)行效率,也就是說(shuō) let 和 const 的本質(zhì)區(qū)別,其實(shí)是編譯器內(nèi)部的處理不同。

// 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 聲明常量還有兩個(gè)好處,一是閱讀代碼的人立刻會(huì)意識(shí)到不應(yīng)該修改這個(gè)值,二是防止了無(wú)意間修改變量值所導(dǎo)致的錯(cuò)誤。

所有的函數(shù)都應(yīng)該設(shè)置為常量。

長(zhǎng)遠(yuǎn)來(lái)看,JavaScript 可能會(huì)有多線程的實(shí)現(xiàn)(比如 Intel 公司的 River Trail 那一類的項(xiàng)目),這時(shí) let 表示的變量,只應(yīng)出現(xiàn)在單線程運(yùn)行的代碼中,不能是多線程共享的,這樣有利于保證線程安全。

2. 字符串

靜態(tài)字符串一律使用單引號(hào)或反引號(hào),不使用雙引號(hào)。動(dòng)態(tài)字符串使用反引號(hào)。

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


// acceptable
const c =  'foobar' ;


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

反引號(hào)(`)這個(gè)符號(hào)在鍵盤的左上角,數(shù)字鍵1的左邊,tab鍵的上方(不同鍵盤的布局可能會(huì)存在差異,這里舉例以美式鍵盤為例,國(guó)內(nèi)大部分使用這種鍵盤),反引號(hào)鍵一般與~為同一個(gè)按鈕。此外反引號(hào)需要在輸入法為英文的時(shí)候才可以打出。

3. 解構(gòu)賦值

使用數(shù)組成員對(duì)變量賦值時(shí),優(yōu)先使用解構(gòu)賦值。

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


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


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

函數(shù)的參數(shù)如果是對(duì)象的成員,優(yōu)先使用解構(gòu)賦值。

// 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 }) {
}

如果函數(shù)返回多個(gè)值,優(yōu)先使用對(duì)象的解構(gòu)賦值,而不是數(shù)組的解構(gòu)賦值。這樣便于以后添加返回值,以及更改返回值的順序。

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


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


const { left, right } = processInput(input);

4. 對(duì)象

單行定義的對(duì)象,最后一個(gè)成員不以逗號(hào)結(jié)尾。多行定義的對(duì)象,最后一個(gè)成員以逗號(hào)結(jié)尾。

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

對(duì)象盡量靜態(tài)化,一旦定義,就不得隨意添加新的屬性。如果添加屬性不可避免,要使用 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;

如果對(duì)象的屬性名是動(dòng)態(tài)的,可以在創(chuàng)造對(duì)象的時(shí)候,使用屬性表達(dá)式定義。

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


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

上面代碼中,對(duì)象 obj 的最后一個(gè)屬性名,需要計(jì)算得到。這時(shí)最好采用屬性表達(dá)式,在新建 obj 的時(shí)候,將該屬性與其他屬性定義在一起。這樣一來(lái),所有屬性就在一個(gè)地方定義了。

另外,對(duì)象的屬性和方法,盡量采用簡(jiǎn)潔表達(dá)法,這樣易于描述和書寫。

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. 數(shù)組

使用擴(kuò)展運(yùn)算符(...)拷貝數(shù)組。

// 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 方法,將類似數(shù)組的對(duì)象轉(zhuǎn)為數(shù)組。

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

6. 函數(shù)

立即執(zhí)行函數(shù)可以寫成箭頭函數(shù)的形式。

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

那些使用匿名函數(shù)當(dāng)作參數(shù)的場(chǎng)合,盡量用箭頭函數(shù)代替。因?yàn)檫@樣更簡(jiǎn)潔,而且綁定了 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);

箭頭函數(shù)取代Function.prototype.bind,不應(yīng)再用 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);

簡(jiǎn)單的、單行的、不會(huì)復(fù)用的函數(shù),建議采用箭頭函數(shù)。如果函數(shù)體較為復(fù)雜,行數(shù)較多,還是應(yīng)該采用傳統(tǒng)的函數(shù)寫法。

所有配置項(xiàng)都應(yīng)該集中在一個(gè)對(duì)象,放在最后一個(gè)參數(shù),布爾值不可以直接作為參數(shù)。

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


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

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

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


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

使用默認(rèn)值語(yǔ)法設(shè)置函數(shù)參數(shù)的默認(rèn)值。

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


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

7. Map 結(jié)構(gòu)

注意區(qū)分 Object 和 Map,只有模擬現(xiàn)實(shí)世界的實(shí)體對(duì)象時(shí),才使用 Object。如果只是需要 key: value的數(shù)據(jù)結(jié)構(gòu),使用 Map 結(jié)構(gòu)。因?yàn)?Map 有內(nèi)建的遍歷機(jī)制。

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 的操作。因?yàn)?Class 的寫法更簡(jiǎn)潔,更易于理解。

// 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實(shí)現(xiàn)繼承,因?yàn)檫@樣更簡(jiǎn)單,不會(huì)有破壞 instanceof 運(yùn)算的危險(xiǎn)。

// 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. 模塊

首先,Module 語(yǔ)法是 JavaScript 模塊的標(biāo)準(zhǔn)寫法,堅(jiān)持使用這種寫法。使用 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;

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

不要在模塊輸入中使用通配符。因?yàn)檫@樣可以確保你的模塊之中,有一個(gè)默認(rèn)輸出(export default)。

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


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

如果模塊默認(rèn)輸出一個(gè)函數(shù),函數(shù)名的首字母應(yīng)該小寫。

function makeStyleGuide() {
}


export default makeStyleGuide;

如果模塊默認(rèn)輸出一個(gè)對(duì)象,對(duì)象名的首字母應(yīng)該大寫。

const StyleGuide = {
  es6: {
  }
};


export default StyleGuide;

10. ESLint 的使用

ESLint是一個(gè)語(yǔ)法規(guī)則和代碼風(fēng)格的檢查工具,可以用來(lái)保證寫出語(yǔ)法正確、風(fēng)格統(tǒng)一的代碼。

首先,安裝 ESLint。

$ npm i -g eslint

然后,安裝 Airbnb 語(yǔ)法規(guī)則,以及 import、a11y、react 插件。

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

最后,在項(xiàng)目的根目錄下新建一個(gè) .eslintrc 文件,配置 ESLint。

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

現(xiàn)在就可以檢查,當(dāng)前項(xiàng)目的代碼是否符合預(yù)設(shè)的規(guī)則。

index.js 文件的代碼如下。

var unusued = 'I have no purpose!';


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


greet();

使用 ESLint 檢查這個(gè)文件,就會(huì)報(bào)出錯(cuò)誤。

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

上面代碼說(shuō)明,原文件有五個(gè)錯(cuò)誤,其中兩個(gè)是不應(yīng)該使用 var 命令,而要使用 letconst ;一個(gè)是定義了變量,卻沒(méi)有使用;另外兩個(gè)是行首縮進(jìn)為 4 個(gè)空格,而不是規(guī)定的 2 個(gè)空格。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)