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)有副作用。

  1. 'use strict';
  2. if (true) {
  3. let x = 'hello';
  4. }
  5. for (let i = 0; i < 10; i++) {
  6. console.log(i);
  7. }

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

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

  1. 'use strict';
  2. if (true) {
  3. console.log(x); // ReferenceError
  4. let x = 'hello';
  5. }

上面代碼如果使用 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)部的處理不同。

  1. // bad
  2. var a = 1, b = 2, c = 3;
  3. // good
  4. const a = 1;
  5. const b = 2;
  6. const c = 3;
  7. // best
  8. 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)。

  1. // bad
  2. const a = "foobar";
  3. const b = 'foo' + a + 'bar';
  4. // acceptable
  5. const c = 'foobar' ;
  6. // good
  7. const a = `foobar`;
  8. 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)賦值。

  1. const arr = [1, 2, 3, 4];
  2. // bad
  3. const first = arr[0];
  4. const second = arr[1];
  5. // good
  6. const [first, second] = arr;

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

  1. // bad
  2. function getFullName(user) {
  3. const firstName = user.firstName;
  4. const lastName = user.lastName;
  5. }
  6. // good
  7. function getFullName(obj) {
  8. const { firstName, lastName } = obj;
  9. }
  10. // best
  11. function getFullName({ firstName, lastName }) {
  12. }

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

  1. // bad
  2. function processInput(input) {
  3. return [left, right, top, bottom];
  4. }
  5. // good
  6. function processInput(input) {
  7. return { left, right, top, bottom };
  8. }
  9. const { left, right } = processInput(input);

4. 對(duì)象

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

  1. // bad
  2. const a = { k1: v1, k2: v2, };
  3. const b = {
  4. k1: v1,
  5. k2: v2
  6. };
  7. // good
  8. const a = { k1: v1, k2: v2 };
  9. const b = {
  10. k1: v1,
  11. k2: v2,
  12. };

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

  1. // bad
  2. const a = {};
  3. a.x = 3;
  4. // if reshape unavoidable
  5. const a = {};
  6. Object.assign(a, { x: 3 });
  7. // good
  8. const a = { x: null };
  9. a.x = 3;

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

  1. // bad
  2. const obj = {
  3. id: 5,
  4. name: 'San Francisco',
  5. };
  6. obj[getKey('enabled')] = true;
  7. // good
  8. const obj = {
  9. id: 5,
  10. name: 'San Francisco',
  11. [getKey('enabled')]: true,
  12. };

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

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

  1. var ref = 'some value';
  2. // bad
  3. const atom = {
  4. ref: ref,
  5. value: 1,
  6. addValue: function (value) {
  7. return atom.value + value;
  8. },
  9. };
  10. // good
  11. const atom = {
  12. ref,
  13. value: 1,
  14. addValue(value) {
  15. return atom.value + value;
  16. },
  17. };

5. 數(shù)組

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

  1. // bad
  2. const len = items.length;
  3. const itemsCopy = [];
  4. let i;
  5. for (i = 0; i < len; i++) {
  6. itemsCopy[i] = items[i];
  7. }
  8. // good
  9. const itemsCopy = [...items];

使用 Array.from 方法,將類似數(shù)組的對(duì)象轉(zhuǎn)為數(shù)組。

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

6. 函數(shù)

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

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

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

  1. // bad
  2. [1, 2, 3].map(function (x) {
  3. return x * x;
  4. });
  5. // good
  6. [1, 2, 3].map((x) => {
  7. return x * x;
  8. });
  9. // best
  10. [1, 2, 3].map(x => x * x);

箭頭函數(shù)取代Function.prototype.bind,不應(yīng)再用 self/_this/that 綁定 this。

  1. // bad
  2. const self = this;
  3. const boundMethod = function(...params) {
  4. return method.apply(self, params);
  5. }
  6. // acceptable
  7. const boundMethod = method.bind(this);
  8. // best
  9. 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ù)。

  1. // bad
  2. function divide(a, b, option = false ) {
  3. }
  4. // good
  5. function divide(a, b, { option = false } = {}) {
  6. }

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

  1. // bad
  2. function concatenateAll() {
  3. const args = Array.prototype.slice.call(arguments);
  4. return args.join('');
  5. }
  6. // good
  7. function concatenateAll(...args) {
  8. return args.join('');
  9. }

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

  1. // bad
  2. function handleThings(opts) {
  3. opts = opts || {};
  4. }
  5. // good
  6. function handleThings(opts = {}) {
  7. // ...
  8. }

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ī)制。

  1. let map = new Map(arr);
  2. for (let key of map.keys()) {
  3. console.log(key);
  4. }
  5. for (let value of map.values()) {
  6. console.log(value);
  7. }
  8. for (let item of map.entries()) {
  9. console.log(item[0], item[1]);
  10. }

8. Class

總是用 Class,取代需要 prototype 的操作。因?yàn)?Class 的寫法更簡(jiǎn)潔,更易于理解。

  1. // bad
  2. function Queue(contents = []) {
  3. this._queue = [...contents];
  4. }
  5. Queue.prototype.pop = function() {
  6. const value = this._queue[0];
  7. this._queue.splice(0, 1);
  8. return value;
  9. }
  10. // good
  11. class Queue {
  12. constructor(contents = []) {
  13. this._queue = [...contents];
  14. }
  15. pop() {
  16. const value = this._queue[0];
  17. this._queue.splice(0, 1);
  18. return value;
  19. }
  20. }

使用 extends實(shí)現(xiàn)繼承,因?yàn)檫@樣更簡(jiǎn)單,不會(huì)有破壞 instanceof 運(yùn)算的危險(xiǎn)。

  1. // bad
  2. const inherits = require('inherits');
  3. function PeekableQueue(contents) {
  4. Queue.apply(this, contents);
  5. }
  6. inherits(PeekableQueue, Queue);
  7. PeekableQueue.prototype.peek = function() {
  8. return this._queue[0];
  9. }
  10. // good
  11. class PeekableQueue extends Queue {
  12. peek() {
  13. return this._queue[0];
  14. }
  15. }

9. 模塊

首先,Module 語(yǔ)法是 JavaScript 模塊的標(biāo)準(zhǔn)寫法,堅(jiān)持使用這種寫法。使用 import 取代 require 。

  1. // bad
  2. const moduleA = require('moduleA');
  3. const func1 = moduleA.func1;
  4. const func2 = moduleA.func2;
  5. // good
  6. import { func1, func2 } from 'moduleA';

使用 export 取代 module.exports 。

  1. // commonJS的寫法
  2. var React = require('react');
  3. var Breadcrumbs = React.createClass({
  4. render() {
  5. return <nav />;
  6. }
  7. });
  8. module.exports = Breadcrumbs;
  9. // ES6的寫法
  10. import React from 'react';
  11. class Breadcrumbs extends React.Component {
  12. render() {
  13. return <nav />;
  14. }
  15. };
  16. export default Breadcrumbs;

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

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

  1. // bad
  2. import * as myObject from './importModule';
  3. // good
  4. import myObject from './importModule';

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

  1. function makeStyleGuide() {
  2. }
  3. export default makeStyleGuide;

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

  1. const StyleGuide = {
  2. es6: {
  3. }
  4. };
  5. export default StyleGuide;

10. ESLint 的使用

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

首先,安裝 ESLint。

  1. $ npm i -g eslint

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

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

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

  1. {
  2. "extends": "eslint-config-airbnb"
  3. }

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

index.js 文件的代碼如下。

  1. var unusued = 'I have no purpose!';
  2. function greet() {
  3. var message = 'Hello, World!';
  4. alert(message);
  5. }
  6. greet();

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

  1. $ eslint index.js
  2. index.js
  3. 1:1 error Unexpected var, use let or const instead no-var
  4. 1:5 error unusued is defined but never used no-unused-vars
  5. 4:5 error Expected indentation of 2 characters but found 4 indent
  6. 4:5 error Unexpected var, use let or const instead no-var
  7. 5:5 error Expected indentation of 2 characters but found 4 indent
  8. ? 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)