1. 塊級作用域
(1)使用let 取代 var
ES6提出了兩個新的聲明變量的命令:let和const。其中,let完全可以取代var,因為兩者語義相同,而且let沒有副作用。
if (true) {
let x = 'hello';
}
for (let i = 0; i < 10; i++) {
console.log(i);
}
//上面代碼如果用var替代let,實際上就聲明了兩個全局變量,這顯然不是本意。變量應該只在其聲明的代碼塊內(nèi)有效,var命令做不到這一點。
var命令存在變量提升效用,let命令沒有這個問題。
if(true) {
console.log(x); // ReferenceError
let x = 'hello';
}
//該代碼如果使用var替代let,console.log那一行就不會報錯,而是會輸出undefined,因為變量聲明提升到代碼塊的頭部。這違反了變量先聲明后使用的原則。
所以,建議不再使用var命令,而是使用let命令取代。
(2)全局常量和線程安全
在let和const之間,建議優(yōu)先使用const,尤其是在全局環(huán)境,不應該設置變量,只應設置常量。
const優(yōu)于let有幾個原因。一個是const可以提醒閱讀程序的人,這個變量不應該改變;另一個是const比較符合函數(shù)式編程思想,運算不改變值,只是新建值,而且這樣也有利于將來的分布式運算;最后一個原因是 JavaScript 編譯器會對const進行優(yōu)化,所以多使用const,有利于提供程序的運行效率,也就是說let和const的本質(zhì)區(qū)別,其實是編譯器內(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聲明常量還有兩個好處,一是閱讀代碼的人立刻會意識到不應該修改這個值,二是防止了無意間修改變量值所導致的錯誤。
所有的函數(shù)都應該設置為常量。
長遠來看,JavaScript可能會有多線程的實現(xiàn)(比如Intel的River Trail那一類的項目),這時let表示的變量,只應出現(xiàn)在單線程運行的代碼中,不能是多線程共享的,這樣有利于保證線程安全。
2. 字符串相關(guān)
靜態(tài)字符串一律使用單引號或反引號,不使用雙引號。動態(tài)字符串使用反引號。
// 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. 結(jié)構(gòu)賦值
//使用數(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ù)如果是對象的成員,優(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ù)返回多個值,優(yōu)先使用對象的解構(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. 數(shù)組相關(guā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ù)組的對象轉(zhuǎn)為數(shù)組。
const foo = document.querySelectorAll('.foo');
const nodes = Array.from(foo);
5. 對象相關(guān)
單行定義的對象,最后一個成員不以逗號結(jié)尾。多行定義的對象,最后一個成員以逗號結(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,
};
對象盡量靜態(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;
如果對象的屬性名是動態(tài)的,可以在創(chuàng)造對象的時候,使用屬性表達式定義。
// 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;
},
};
6. 函數(shù)相關(guān)
立即執(zhí)行函數(shù)可以寫成箭頭函數(shù)的形式。
(() => {
console.log('Welcome to the Internet.');
})();
那些需要使用函數(shù)表達式的場合,盡量用箭頭函數(shù)代替。因為這樣更簡潔,而且綁定了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,不應再用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);
簡單的、單行的、不會復用的函數(shù),建議采用箭頭函數(shù)。如果函數(shù)體較為復雜,行數(shù)較多,還是應該采用傳統(tǒng)的函數(shù)寫法。
所有配置項都應該集中在一個對象,放在最后一個參數(shù),布爾值不可以直接作為參數(shù)。
// bad
function divide(a, b, option = false ) {
}
// good
function divide(a, b, { option = false } = {}) {
}
不要在函數(shù)體內(nèi)使用arguments變量,使用rest運算符(...)代替。因為rest運算符顯式表明你想要獲取參數(shù),而且arguments是一個類似數(shù)組的對象,而rest運算符可以提供一個真正的數(shù)組。
// bad
function concatenateAll() {
const args = Array.prototype.slice.call(arguments);
return args.join('');
}
// good
function concatenateAll(...args) {
return args.join('');
}
使用默認值語法設置函數(shù)參數(shù)的默認值。
// bad
function handleThings(opts) {
opts = opts || {};
}
// good
function handleThings(opts = {}) {
// ...
}
7. map結(jié)構(gòu)相關(guān)
注意區(qū)分Object和Map,只有模擬現(xiàn)實世界的實體對象時,才使用Object。如果只是需要key: value的數(shù)據(jù)結(jié)構(gòu),使用Map結(jié)構(gòu)。因為Map有內(nèi)建的遍歷機制。
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實現(xiàn)繼承,因為這樣更簡單,不會有破壞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];
}
}
9. 模塊相關(guān)
首先,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';
const Breadcrumbs = React.createClass({
render() {
return <nav />;
}
});
export default Breadcrumbs
如果模塊只有一個輸出值,就使用export default,如果模塊有多個輸出值,就不使用export default,不要export default與普通的export同時使用。
不要在模塊輸入中使用通配符。因為這樣可以確保你的模塊之中,有一個默認輸出(export default)。
// bad
import * as myObject './importModule';
// good
import myObject from './importModule';
如果模塊默認輸出一個函數(shù),函數(shù)名的首字母應該小寫。
function makeStyleGuide() {
}
export default makeStyleGuide;
如果模塊默認輸出一個對象,對象名的首字母應該大寫。
const StyleGuide = {
es6: {
}
};
export default StyleGuide;