ECMAScript6 規範

1、塊級做用域node

(1)let 取代 varreact

ES6提出了兩個新的聲明變量的命令:let和const。其中,let徹底能夠取代var,由於二者語義相同,並且let沒有反作用。es6

'use strict';if (true) {
  let x = 'hello';
}for (let i = 0; i < 10; i++) {
  console.log(i);
}

上面代碼若是用var替代let,實際上就聲明瞭兩個全局變量,這顯然不是本意。變量應該只在其聲明的代碼塊內有效,var命令作不到這一點。npm

var命令存在變量提高效用,let命令沒有這個問題。編程

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

上面代碼若是使用var替代let,console.log那一行就不會報錯,而是會輸出undefined,由於變量聲明提高到代碼塊的頭部。這違反了變量先聲明後使用的原則。數組

因此,建議再也不使用var命令,而是使用let命令取代安全

 

(2)全局常量和線程安全數據結構

在let和const之間,建議優先使用const,尤爲是在全局環境,不該該設置變量,只應設置常量。多線程

const優於let有幾個緣由。一個是const能夠提醒閱讀程序的人,這個變量不該該改變;另外一個是const比較符合函數式編程思想,運算不改變值,只是新建值,並且這樣也有利於未來的分佈式運算;最後一個緣由是 JavaScript 編譯器會對const進行優化,因此多使用const,有利於提供程序的運行效率,也就是說let和const的本質區別,實際上是編譯器內部的處理不一樣。app

// badvar a = 1, b = 2, c = 3;// goodconst a = 1;
const b = 2;
const c = 3;// best

const聲明常量還有兩個好處,一是閱讀代碼的人馬上會意識到不該該修改這個值,二是防止了無心間修改變量值所致使的錯誤。

全部的函數都應該設置爲常量。

長遠來看,JavaScript可能會有多線程的實現(好比Intel的River Trail那一類的項目),這時let表示的變量,只應出如今單線程運行的代碼中,不能是多線程共享的,這樣有利於保證線程安全。

 

2、字符串

靜態字符串一概使用單引號或反引號,不使用雙引號。動態字符串使用反引號。

// badconst a = "foobar";
const b = 'foo' + a + 'bar';// acceptableconst c = `foobar`;// goodconst a = 'foobar';
const b = `foo${a}bar`;
const c = 'foobar';

 

3、解構賦值

使用數組成員對變量賦值時,優先使用解構賦值。

const arr = [1, 2, 3, 4];// badconst first = arr[0];
const second = arr[1];// goodconst [first, second] = arr;

函數的參數若是是對象的成員,優先使用解構賦值。

// badfunction getFullName(user) {
  const firstName = user.firstName;
  const lastName = user.lastName;
}// goodfunction getFullName(obj) {
  const { firstName, lastName } = obj;
}// bestfunction getFullName({ firstName, lastName }) {
}

若是函數返回多個值,優先使用對象的解構賦值,而不是數組的解構賦值。這樣便於之後添加返回值,以及更改返回值的順序。

// badfunction processInput(input) {  return [left, right, top, bottom];
}// goodfunction processInput(input) {  return { left, right, top, bottom };
}
const { left, right } = processInput(input);

 

4、對象

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

// badconst a = { k1: v1, k2: v2, };
const b = {
  k1: v1,
  k2: v2
};// goodconst a = { k1: v1, k2: v2 };
const b = {
  k1: v1,
  k2: v2,
};

對象儘可能靜態化,一旦定義,就不得隨意添加新的屬性。若是添加屬性不可避免,要使用Object.assign方法。

// badconst a = {};
a.x = 3;// if reshape unavoidableconst a = {};
Object.assign(a, { x: 3 });// goodconst a = { x: null };
a.x = 3;

若是對象的屬性名是動態的,能夠在創造對象的時候,使用屬性表達式定義。

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

上面代碼中,對象obj的最後一個屬性名,須要計算獲得。這時最好採用屬性表達式,在新建obj的時候,將該屬性與其餘屬性定義在一塊兒。這樣一來,全部屬性就在一個地方定義了。

另外,對象的屬性和方法,儘可能採用簡潔表達法,這樣易於描述和書寫。

var ref = 'some value';// badconst atom = {
  ref: ref,
  value: 1,
  addValue: function (value) {    return atom.value + value;
  },
};// goodconst atom = {
  ref,
  value: 1,
  addValue(value) {    return atom.value + value;
  },
};

 

5、數組

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

// badconst len = items.length;
const itemsCopy = [];
let i;for (i = 0; i < len; i++) {
  itemsCopy[i] = items[i];
}// goodconst itemsCopy = [...items];

使用Array.from方法,將相似數組的對象轉爲數組。

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

 

6、函數

當即執行函數能夠寫成箭頭函數的形式。

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

那些須要使用函數表達式的場合,儘可能用箭頭函數代替。由於這樣更簡潔,並且綁定了

// 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);

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

// badconst self = this;
const boundMethod = function(...params) {  return method.apply(self, params);
}// acceptableconst boundMethod = method.bind(this);// bestconst boundMethod = (...params) => method.apply(this, params);

簡單的、單行的、不會複用的函數,建議採用箭頭函數。若是函數體較爲複雜,行數較多,仍是應該採用傳統的函數寫法。

全部配置項都應該集中在一個對象,放在最後一個參數,布爾值不能夠直接做爲參數。

// badfunction divide(a, b, option = false ) {
}// goodfunction divide(a, b, { option = false } = {}) {
}

不要在函數體內使用arguments變量,使用rest運算符(...)代替。由於rest運算符顯式代表你想要獲取參數,並且arguments是一個相似數組的對象,而rest運算符能夠提供一個真正的數組。

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

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

// badfunction handleThings(opts) {
  opts = opts || {};
}// goodfunction handleThings(opts = {}) { // ...}

 

7、Map結構

注意區分Object和Map,只有模擬現實世界的實體對象時,才使用Object。若是隻是須要key: value的數據結構,使用Map結構。由於Map有內建的遍歷機制。

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的寫法更簡潔,更易於理解。

// badfunction Queue(contents = []) {  this._queue = [...contents];
}
Queue.prototype.pop = function() {
  const value = this._queue[0];  this._queue.splice(0, 1);  return value;
}// goodclass Queue {
  constructor(contents = []) {    this._queue = [...contents];
  }
  pop() {
    const value = this._queue[0];    this._queue.splice(0, 1);    return value;
  }
}

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

// badconst inherits = require('inherits');function PeekableQueue(contents) {
  Queue.apply(this, contents);
}
inherits(PeekableQueue, Queue);
PeekableQueue.prototype.peek = function() {  return this._queue[0];
}// goodclass PeekableQueue extends Queue {
  peek() {    return this._queue[0];
  }
}

 

9、模塊

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

const moduleA = require('moduleA');
const func1 = moduleA.func1;
const func2 = moduleA.func2;// goodimport { 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)。

// badimport * as myObject './importModule';// goodimport myObject from './importModule';

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

function makeStyleGuide() {
}
export default makeStyleGuide;

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

const StyleGuide = {
  es6: {
  }
};
export default StyleGuide;

 

10、ESLint的使用

ESLint是一個語法規則和代碼風格的檢查工具,能夠用來保證寫出語法正確、風格統一的代碼。

首先,安裝ESLint。

npm i -g eslint

而後,安裝Airbnb語法規則。

npm i -g eslint-config-airbnb

最後,在項目的根目錄下新建一個.eslintrc文件,配置ESLint。

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

index.js文件的代碼以下。

var unusued = 'I have no purpose!';function greet() {    var message = 'Hello, World!';
    alert(message);
}
greet();

使用ESLint檢查這個文件。

eslint index.js
index.js  1:5  error  unusued is defined but never used                 no-unused-vars  4:5  error  Expected indentation of 2 characters but found 4  indent  5:5  error  Expected indentation of 2 characters but found 4  indent
 3 problems (3 errors, 0 warnings)

上面代碼說明,原文件有三個錯誤,一個是定義了變量,卻沒有使用,另外兩個是行首縮進爲4個空格,而不是規定的2個空格

相關文章
相關標籤/搜索