塊級作用域
用let全面取代var
全局使用常量
// bad
var a=2,b=2,c=3
//best
const [a,b,c]=[1,2,3]
字符串
多用模板字符串
// bad
const a = "foobar";
const b = 'foo' + a + 'bar';
//best
const a="foobar"
const b=`foo${a}bar`//foofoobarbar
使用解構賦值
數組成員成對賦值時
const arr = [1, 2, 3, 4];
//bad
const first=arr[0]
const second=arr[1]
//best
const [first,second]=arr
函數的參數是對象的成員
// bad
function getFullName(obj) {
const firstName = obj.firstName;
const lastName = obj.lastName;
}
//good
function getFullName(obj) {
const { firstName, lastName } = obj;
}
//best
function getFullName({firstName, lastName}) {
}
函數多個返回值時,優先使用對象的解構.
不建議數組的解構,好處是以便後續添加和修改.
// bad
function processInput() {
return [left, right, top, bottom];
}
//good
function processInput() {
return {left, rigit, top, bottom}
}
對象
單行和多行寫法
// 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,//多行以逗號結尾
}
靜態化
// bad
const a = {};
a.x = 3;
//good
const a = {}
Object.assign(a, { x: 3 })//對象的合併方法
//或者下面寫法
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('enable')]:true
}
屬性和方法名,使用簡介寫法
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 = [];
for (let i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
// good
const itemsCopy = [...items];
使用Array.from(對象),可以把僞數組或者類似數組的對象轉換爲真數組
//案例1
const foo = document.querySelectorAll('.foo');
const nodes = Array.from(foo);
//案例2
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
//轉成真數組
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
函數
使用箭頭函數
// bad
[1, 2, 3].map(function (x) {
return x * x;
});
//best
[1, 2, 3].map(x => x * x) // [1, 4, 9]
箭頭函數直接綁定this
// bad
const self = this;
const boundMethod = function(...params) {
return method.apply(self, params);
}
//best
const boundMethod=(...params)=>{method.apply(this,params)}
使用…arg代替arguments 變量
// bad
function concatenateAll1() {
console.log(arguments);//arguments對象
const args = Array.prototype.slice.call(arguments);//slice截取,得到args數組[1, 2, 3]
console.log(args);
return console.log(args.join(''));//字符串:123
;
}
// good
function concatenateAll2(...args) {
return console.log(args.join(''));//同樣得到字符串:123
}
concatenateAll2(1,2,3)
使用默認值語法設置函數參數的默認值
// bad
function handleThings(opts) {
opts = opts || {};
}
// good
function handleThings(opts = {}) {
// ...
}
class類
使用class類取代 prototype 的操作
// bad
function Queue1(contents = []) {
this._queue = [...contents];
}
Queue1.prototype.pop = function() {
const value = this._queue[0];
this._queue.splice(0, 1);//slice截取
return value;
}
// good
class Queue2 {
constructor(contents = []) {
this._queue = [...contents];
}
pop() {
const value = this._queue[0];
this._queue.splice(0, 1);
return value;
}
}
console.log(new Queue1([1,2,3]).pop());//1
console.log(new Queue2([1,2,3]).pop());//1
使用繼承
// good
class PeekableQueue extends Queue {
peek() {
return this._queue[0];
}
}
模塊
使用es6導入導出
//es6導入
import { func1, func2 } from 'moduleA';
es6導出
import React from 'react';
class Breadcrumbs extends React.Component {
render() {
return <nav />;
}
};
export default Breadcrumbs;
模塊小細節
不要在模塊輸入中使用通配符。因爲這樣可以確保你的模塊之中,有一個默認輸出(export default)
// bad
import * as myObject from './importModule';
// good
import myObject from './importModule';
如果模塊默認輸出一個函數,函數名的首字母應該小寫。
function makeStyleGuide() {
}
export default makeStyleGuide;
如果模塊默認輸出一個對象,對象名的首字母應該大寫。
const StyleGuide = {
es6: {
}
};
export default StyleGuide;