ES6編碼風格

JavaScript

一、塊級作用域

1.1 let取代var

ES6提出了兩個新的聲明變量的命令:let和const。其中,let完全可以取代var,因為兩者語義相同,而且let沒有副作用

var命令存在變量提升效用,let命令沒有這個問題

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

1

2

3

4

5

"use strict";

if(true) {

console.log(x);// ReferenceError

letx ='hello';

}

上面代碼如果使用var替代let,console.log那一行就不會報錯,而是會輸出undefined,因為變量聲明提

升到代碼塊的頭部。這違反了變量先聲明后使用的原則

1.2 全局常量和線程安全

在let和const之間,建議優(yōu)先使用const,尤其是在全局環(huán)境,不應該設置變量,只應設置常量。這符合函數式編程思想,有利于將來的分布式運算。

1

2

3

4

5

6

7

8

9

10

// bad

vara =1, b =2, c =3;

// good

consta =1;

constb =2;

constc =3;

// best

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

const聲明常量還有兩個好處,一是閱讀代碼的人立刻會意識到不應該修改這個值,二是防止了無意間修改

變量值所導致的錯誤

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

let表示的變量,只應出現在單線程運行的代碼中,不能是多線程共享的,這樣有利于保證線程安全

1.3 嚴格模式

V8引擎只在嚴格模式之下,支持let和const。結合前兩點,這實際上意味著,將來所有的編程都是針對嚴

格模式的。

二、字符串

靜態(tài)字符串一律使用單引號,不使用雙引號。動態(tài)字符串使用反引號

1

2

3

4

5

6

7

8

9

// bad

consta ="foobar";

constb ='foo'+ a +'bar';

// good

consta ='foobar';

constb =`foo${a}bar`;

constc ='foobar';

三、解構賦值

使用數組成員對變量賦值,優(yōu)先使用解構賦值

1

2

3

4

5

6

7

8

constarr = [1,2,3,4];

// bad

constfirst = arr[0];

constsecond = arr[1];

// good

const[first, second] = arr;

函數的參數如果是對象的成員,優(yōu)先使用解構賦值

1

2

3

4

5

6

7

8

9

10

11

12

13

14

// bad

functiongetFullName(user){

constfirstName = user.firstName;

constlastName = user.lastName;

}

// good

functiongetFullName(obj){

const{ firstName, lastName } = obj;

}

// best

functiongetFullName({ firstName, lastName }){

}

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

1

2

3

4

5

6

7

8

9

10

// bad

functionprocessInput(input){

return[left, right, top, bottom];

}

// good

functionprocessInput(input){

return{ left, right, top, bottom };

}

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

四、對象

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

1

2

3

4

5

6

7

8

9

10

11

12

13

// bad

consta = {k1: v1,k2: v2, };

constb = {

k1: v1,

k2: v2

};

// good

consta = {k1: v1,k2: v2 };

constb = {

k1: v1,

k2: v2,

};

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

1

2

3

4

5

6

7

8

9

10

11

// bad

consta = {};

a.x =3;

// if reshape unavoidable

consta = {};

Object.assign(a, {x:3});

// good

consta = {x:null};

a.x =3

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

1

2

3

4

5

6

7

8

9

10

11

12

13

// bad

constobj = {

id:5,

name:'San Francisco',

};

obj[getKey('enabled')] =true;'

// good

const obj = {

id: 5,

name: 'San Francisco',

[getKey('enabled')]: true,

};

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

ar ref ='some value';

// bad

constatom = {

ref: ref,

value:1,

addValue:function(value){

returnatom.value + value;

},

};

// good

constatom = {

ref,

value:1,

addValue(value) {

returnatom.value + value;

},

};

五、數組

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

1

2

3

4

5

6

7

8

9

10

// bad

constlen = items.length;

constitemsCopy = [];

leti;

for(i =0; i < len; i++) {

itemsCopy[i] = items[i];

}

// good

constitemsCopy = [...items];

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

1

2

constfoo =document.querySelectorAll('.foo');

constnodes =Array.from(foo);

六、函數

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

1

2

3

(()=>{

console.log('Welcome to the Internet.');

})();

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

1

2

3

4

5

6

7

8

9

// bad

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

returnx * x;

});

// good

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

returnx * x;

});

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

1

2

3

4

5

6

7

8

9

10

11

// bad

constself =this;

constboundMethod =function(...params){

returnmethod.apply(self, params);

}

// acceptable

constboundMethod = method.bind(this);

// best

constboundMethod =(...params) =>method.apply(this, params);

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

1

2

3

4

5

6

7

// bad

functiondivide(a, b, option = false){

}

// good

functiondivide(a, b, { option = false } = {}){

}

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

1

2

3

4

5

6

7

8

9

10

// bad

functionconcatenateAll(){

constargs =Array.prototype.slice.call(arguments);

returnargs.join('');

}

// good

functionconcatenateAll(...args){

returnargs.join('');

}

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

1

2

3

4

5

6

7

8

9

// bad

functionhandleThings(opts){

opts = opts || {};

}

// good

functionhandleThings(opts = {}){

// ...

}

七、Map結構

注意區(qū)分Object和Map,只有模擬實體對象時,才使用Object。如果只是需要key:value的數據結構,使用Map。因為Map有內建的遍歷機制

1

2

3

4

5

6

7

8

9

10

letmap =newMap(arr);

for(letkeyofmap.keys()) {

console.log(key);

}

for(letvalueofmap.values()) {

console.log(value);

}

for(letitemofmap.entries()) {

console.log(item[0], item[1]);

}

八、Class

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

// bad

functionQueue(contents = []){

this._queue = [...contents];

}

Queue.prototype.pop =function(){

constvalue =this._queue[0];

this._queue.splice(0,1);

returnvalue;

}

// good

classQueue{

constructor(contents = []) {

this._queue = [...contents];

}

pop() {

constvalue =this._queue[0];

this._queue.splice(0,1);

returnvalue;

}

}

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

// bad

constinherits =require('inherits');

functionPeekableQueue(contents){

Queue.apply(this, contents);

}

inherits(PeekableQueue, Queue);

PeekableQueue.prototype.peek =function(){

returnthis._queue[0];

}

// good

classPeekableQueueextendsQueue{

peek() {

returnthis._queue[0];

}

}

九、模塊

Module語法是JavaScript模塊的標準寫法,堅持使用這種寫法。使用import取代require

1

2

3

4

5

6

7

// bad

constmoduleA =require('moduleA');

constfunc1 = moduleA.func1;

constfunc2 = moduleA.func2;

// good

import{ func1, func2 }from'moduleA';

使用export取代module.exports

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

// commonJS的寫法

varReact =require('react');

varBreadcrumbs = React.createClass({

render() {

return;

}

});

module.exports = Breadcrumbs;

// ES6的寫法

import React from 'react';

const Breadcrumbs = React.createClass({

render() {

return;

}

});

export default Breadcrumbs

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

1

2

3

4

5

// bad

import*asmyObject'./importModule';

// good

importmyObjectfrom'./importModule';

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

1

2

3

functionmakeStyleGuide(){

}

exportdefaultmakeStyleGuide;

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

1

2

3

4

5

constStyleGuide = {

es6: {

}

};

exportdefaultStyleGuide;

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容