es6提出了let和const,但在let和const之間優先選擇const,尤其是在全局環境,不應該設置變量,只應該設置常量。
const優於let有幾個原因。一個是const可以提醒閱讀程序的人,這個變量不應該改變;另一個是const比較符合函數式編程思想,運算不改變值,只是新建值,而且這樣也有利於將來的分布式運算;最后一個原因是 JavaScript 編譯器會對const進行優化,所以多使用const,有利於提高程序的運行效率,也就是說let和const的本質區別,其實是編譯器內部的處理不同。
靜態字符串一律使用單引號或反引號,不使用雙引號。動態字符串使用反引號。
// bad const a = "foobar"; const b = 'foo' + a + 'bar'; // acceptable const c = `foobar`; // good const a = 'foobar'; const b = `foo${a}bar`;
使用數組成員對變量賦值時,優先使用解構賦值。函數的參數如果是對象的成員,優先使用解構賦值。
如果函數返回多個值,優先使用對象的解構賦值,而不是數組的解構賦值。這樣便於以后添加返回值,以及更改返回值的順序
// bad function processInput(input) { return [left, right, top, bottom]; } // good function processInput(input) { return { left, right, top, bottom }; } const { left, right } = processInput(input);
單行定義的對象,最后一個成員不以逗號結尾。多行定義的對象,最后一個成員以逗號結尾。
// 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, };
對象盡量靜態化,一旦定義,就不得隨意添加新的屬性。如果添加屬性不可避免,要使用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;
立即執行函數可以寫成箭頭函數的形式。
(() => { console.log('Welcome to the Internet.'); })();
那些使用匿名函數當作參數的場合,盡量用箭頭函數代替。因為這樣更簡潔,而且綁定了 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);
箭頭函數取代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);
不要在函數體內使用 arguments 變量,使用 rest 運算符(...)代替。因為 rest 運算符顯式表明你想要獲取參數,而且 arguments 是一個類似數組的對象,而 rest 運算符可以提供一個真正的數組。
// bad function concatenateAll() { const args = Array.prototype.slice.call(arguments); return args.join(''); } // good function concatenateAll(...args) { return args.join(''); }
