Node.js 風格指南

jopen 9年前發布 | 30K 次閱讀 Node.js Node.js 開發

  • 參考資料
  • 類型
  • 對象
  • 數組
  • 字符串
  • 函數
  • 屬性
  • 變量
  • Requires
  • 回調函數
  • Try catch
  • 提升
  • 條件表達式 & 相等性
  • 代碼塊
  • 注釋
  • 空格
  • 逗號
  • 分號作為語句塊的結束
  • 類型轉換 & 強制類型轉換
  • 命名約定
  • 訪問器
  • 構造函數
  • ES6箭頭函數
  • ES6增強的對象字面量
  • ES6模板字符串
  • ES6函數參數增強
  • ES6新增關鍵字let和const
  • ES6迭代器和for..of
  • ES6生成器
  • ES6模塊
  • ES6新增集合Map和Set
  • ES6 Promise
  • 推薦的書
  • 推薦的博客

    • };
    • </ul> </li> </ul>

      參考資料

      • Airbnb styleguide
      • RisingStack's Node.js styleguide
      • Caolan's Node.js styleguide
      • Felixge's Node.js styleguide
      • Baidu EFE: ES6 develop overview
      • </ul>

        類型

        • 原始類型: 當你訪問一個原始數據類型時,你直接操作的是它的值

          • string
          • number
          • boolean
          • null
          • undefined
          • </ul>

            var foo = 1; var bar = foo;

            bar = 9; console.log(foo, bar); // => 1, 9</pre></div> </li> </ul>

            • 復雜情況: 當你訪問的是一個復雜類型時,你操作的是它的引用

              • object
              • array
              • function
              • </ul>

                var foo = [1, 2]; var bar = foo;

                bar[0] = 9; console.log(foo[0], bar[0]); // => 9, 9</pre></div> </li> </ul>

                ? back to top

                對象

                • 在對象創建時使用字面量語法

                  // bad var item = new Object(); // good var item = {};
                  </li>

                • 使用可讀的別名,避免使用保留字

                  // bad var superman = {
                    class: 'alien' }; // bad var superman = {
                    klass: 'alien' }; // good var superman = {
                    type: 'alien' };
                  </li> </ul>

                  ? back to top

                  數組

                  • 使用字面量語法創建數組

                    // bad var items = new Array(); // good var items = [];
                    </li>

                  • 當你不知道數組的長度時使用Array#push.

                    var someStack = []; // bad someStack[someStack.length] = 'abracadabra'; // good someStack.push('abracadabra');
                    </li>

                  • 當你需要復制數據時使用Array#slice. jsPerf

                    var len = items.length; var itemsCopy = []; var i; // bad for (i = 0; i < len; i++) {
                      itemsCopy[i] = items[i];
                    } // good itemsCopy = items.slice();
                    </li>

                  • 將一個類數組對象轉為數組,使用Array#slice.

                    function trigger() { var args = Array.prototype.slice.call(arguments);
                      ...
                    }
                    </li> </ul>

                    ? back to top

                    字符串

                    • 使用單引號''表示字符串

                      // bad var name = "Bob Parr"; // good var name = 'Bob Parr'; // bad var fullName = "Bob " + this.lastName; // good var fullName = 'Bob ' + this.lastName;
                      </li>

                    • 長于80個字符的字符串應該被寫成多行(使用字符串拼接或ES6的模板字符串)

                      </li>

                    • 注意:如果過度使用,長字符串拼接會影響性能. jsPerf & Discussion

                      // bad var errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.'; // bad var errorMessage = 'This is a super long error that was thrown because \ of Batman. When you stop to think about how Batman had anything to do \ with this, you would get nowhere \ fast.'; // good var errorMessage = 'This is a super long error that was thrown because ' + 'of Batman. When you stop to think about how Batman had anything to do ' + 'with this, you would get nowhere fast.'; // good var errorMessage = `  hello  world  this  is `;
                      </li>

                    • 當使用程序來生成字符串時,使用Array#join,而不是字符串拼接.

                      var items; var messages; var length; var i;

                      messages = [{ state: 'success'</span>, message: 'This one worked.'</span> }, { state: 'success'</span>, message: 'This one worked as well.'</span> }, { state: 'error'</span>, message: 'This one did not work.'</span> }];

                      length = messages.length; // bad function inbox(messages) { items = '<ul>'</span>; for (i = 0; i < length; i++) { items += '<li>'</span> + messages[i].message + '</li>'</span>; } return items + '</ul>'</span>; } // good function inbox(messages) { items = []; for (i = 0; i < length; i++) { items[i] = messages[i].message; } return '<ul><li>'</span> + items.join('</li><li>'</span>) + '</li></ul>'</span>; }</pre></div> </li> </ul>

                      ? back to top

                      函數

                      • 函數表達式:

                        // anonymous function expression var anonymous = function() { return true;
                        }; // named function expression var named = function named() { return true;
                        }; // immediately-invoked function expression (IIFE) (function() { console.log('Welcome to the Internet. Please follow me.');
                        })();
                        </li>

                      • 永遠不要再一個非函數語句塊內使用函數聲明(if, while, 等). 將函數賦值給一個變量.

                        // bad if (currentUser) { function test() { console.log('Nope.');
                          }
                        } // good var test; if (currentUser) { test = function test() { console.log('Yup.');
                          };
                        }
                        </li>

                      • 永遠不要將你的參數命名為arguments, 這會與函數范圍內的arguments對象沖突.

                        // bad function nope(name, options, arguments) { // ...stuff... } // good function yup(name, options, args) { // ...stuff... }
                        </li> </ul>

                        ? back to top

                        屬性

                        • 當訪問屬性時請使用.操作符.

                          var luke = {
                            jedi: true,
                            age: 28 }; // bad var isJedi = luke['jedi']; // good var isJedi = luke.jedi;
                          </li>

                        • 當你要用變量訪問屬性時,請使用[].

                          var luke = {
                            jedi: true,
                            age: 28 }; function getProp(prop) { return luke[prop];
                          } var isJedi = getProp('jedi');
                          </li> </ul>

                          ? back to top

                          變量

                          • 始終使用var來聲明變量. 否則會創建全局變量,污染全局命名空間.

                            // bad superPower = new SuperPower(); // good var superPower = new SuperPower();
                            </li>

                          • 聲明變量時使用一個新行, 并且每一行都使用var來聲明.

                            // bad var items = getItems(),
                                  goSportsTeam = true,
                                  dragonball = 'z'; // good var items = getItems(); var goSportsTeam = true; var dragonball = 'z';
                            </li>

                          • 最后聲明未賦值的便利. 后面如果你要使用前面的變量進行賦值時會顯得很便利.

                            // bad var i; var items = getItems(); var dragonball; var goSportsTeam = true; var len; // good var items = getItems(); var goSportsTeam = true; var dragonball; var length; var i;
                            </li>

                          • 避免冗余的變量聲明, 可已使用Object對象來構建命名空間.

                            // bad var kaleidoscopeName = '..'; var kaleidoscopeLens = []; var kaleidoscopeColors = []; // good var kaleidoscope = {
                              name: '..',
                              lens: [],
                              colors: []
                            };
                            </li>

                          • 在變量作用范圍的最頂端聲明變量. 這可以幫你避免賦值提升的問題.

                            // bad function() { test(); console.log('doing stuff..'); //..other stuff.. var name = getName(); if (name === 'test') { return false;
                              } return name;
                            } // good function() { var name = getName(); test(); console.log('doing stuff..'); //..other stuff.. if (name === 'test') { return false;
                              } return name;
                            } // bad function() { var name = getName(); if (!arguments.length) { return false;
                              } return true;
                            } // good function() { if (!arguments.length) { return false;
                              } var name = getName(); return true;
                            }
                            </li> </ul>

                            Requires

                            • 使用如下順序來組織node代碼中的require語句:

                              • core modules
                              • npm modules
                              • others
                              • </ul>

                                // bad var Car = require('./models/Car'); var async = require('async'); var http = require('http'); // good var http = require('http'); var fs = require('fs'); var async = require('async'); var mongoose = require('mongoose'); var Car = require('./models/Car');
                                </li>

                              • 當你引入模塊時,不要加.js后綴

                                  // bad var Batmobil = require('./models/Car.js'); // good var Batmobil = require('./models/Car');
                                </li> </ul>

                                ? back to top

                                回調函數

                                • 在回調函數中要始終檢測錯誤

                                  //bad database.get('pokemons', function(err, pokemons) { console.log(pokemons);
                                  }); //good database.get('drabonballs', function(err, drabonballs) { if (err) { // handle the error somehow, maybe return with a callback return console.log(err);
                                    } console.log(drabonballs);
                                  });
                                  </li>

                                • 遇到錯誤時從回調中返回

                                  //bad database.get('drabonballs', function(err, drabonballs) { if (err) { // if not return here console.log(err);
                                    } // this line will be executed as well console.log(drabonballs);
                                  }); //good database.get('drabonballs', function(err, drabonballs) { if (err) { // handle the error somehow, maybe return with a callback return console.log(err);
                                    } console.log(drabonballs);
                                  });
                                  </li>

                                • 當你要開發接口給外部時,在你的回調函數中使用描述性的參數。它能夠讓你的代碼更可讀。

                                  // bad function getAnimals(done) {
                                    Animal.get(done);
                                  } // good function getAnimals(done) {
                                    Animal.get(function(err, animals) { if(err) { return done(err);
                                      } return done(null, {
                                        dogs: animals.dogs,
                                        cats: animals.cats
                                      })
                                    });
                                  }
                                  </li> </ul>

                                  ? back to top

                                  Try catch

                                  • 只能在同步函數中使用throw

                                    Try-catch 語句塊不能被用在異步代碼塊中。

                                    //bad function readPackageJson (callback) {
                                      fs.readFile('package.json', function(err, file) { if (err) { throw err;
                                        }
                                        ...
                                      });
                                    } //good function readPackageJson (callback) {
                                      fs.readFile('package.json', function(err, file) { if (err) { return callback(err);
                                        }
                                        ...
                                      });
                                    }
                                    </li>

                                  • 在同步調用中捕獲錯誤,JSON.parse()應該使用try-catch語句塊

                                    //bad var data = JSON.parse(jsonAsAString); //good var data; try {
                                      data = JSON.parse(jsonAsAString);
                                    } catch (e) { //handle error - hopefully not with a console.log ;) console.log(e);
                                    }
                                    </li> </ul>

                                    ? back to top

                                    提升

                                    • 變量聲明會被提升到作用域的頂端,而賦值操作則不會。

                                      // 先看個簡單的例子,顯然它會拋出錯誤 function example() { console.log(notDefined); // => throws a ReferenceError } // 我們先使用了一個變量,而后再聲明并初始化這個變量 // 輸出結果沒有報錯,而是 `undefined`,意思是未被初始化 function example() { console.log(declaredButNotAssigned); // => undefined var declaredButNotAssigned = true;
                                      } // 變量聲明部分會被提升,賦值部分仍保持不變 // 上面的代碼等同于 function example() { var declaredButNotAssigned; console.log(declaredButNotAssigned); // => undefined declaredButNotAssigned = true;
                                      }
                                      </li>

                                    • 匿名函數表達式會提升它們的變量名,但是函數賦值部門不會被提升

                                      function example() { console.log(anonymous); // => undefined anonymous(); // => TypeError anonymous is not a function var anonymous = function() { console.log('anonymous function expression');
                                        };
                                      }
                                      </li>

                                    • 命名函數表達式會提升它們的變量名,但函數名或函數體不會被提升。

                                      function example() { console.log(named); // => undefined named(); // => TypeError named is not a function superPower(); // => ReferenceError superPower is not defined var named = function superPower() { console.log('Flying');
                                        };
                                      } // the same is true when the function name // is the same as the variable name. function example() { console.log(named); // => undefined named(); // => TypeError named is not a function var named = function named() { console.log('named');
                                        }
                                      }
                                      </li>

                                    • 函數聲明會被整體提升到作用域頂端

                                      function example() {
                                        superPower(); // => Flying function superPower() { console.log('Flying');
                                        }
                                      }
                                      </li>

                                    • 更多信息請參考 JavaScript Scoping & Hoisting by Ben Cherry

                                      </li> </ul>

                                      ? back to top

                                      條件表達式 & 相等性

                                      • 使用===和!==來代替==和!=.
                                      • 條件表達式會被使用ToBoolean方法進行強制類型轉換。并且服從如下規則:

                                        • Objects 被轉換為 true
                                        • Undefined 被轉換為 false
                                        • Null 被轉換為 false
                                        • Booleans 被轉換為 實際的boolean值
                                        • Numbers 被轉換為 false 如果是 +0, -0, or NaN, 其他都為 true
                                        • Strings 被轉換為 false 如果是空字符串'', 其他都為 true
                                        • </ul>

                                          if ([0]) { // true // 數組是對象,對象始終被轉換為 `true` }
                                          </li>

                                        • 使用縮減版.

                                          // bad if (name !== '') { // ...stuff... } // good if (name) { // ...stuff... } // bad if (collection.length > 0) { // ...stuff... } // good if (collection.length) { // ...stuff... }
                                          </li>

                                        • 更多信息請參考 Truth Equality and JavaScript by Angus Croll

                                          </li> </ul>

                                          ? back to top

                                          代碼塊

                                          • 所有的多行代碼塊都要使用大括號,并且不要寫在一行

                                            // bad if (test) return false; // bad if (test) return false; // good if (test) { return false;
                                            } // bad function() { return false; } // good function() { return false;
                                            }
                                            </li> </ul>

                                            ? back to top

                                            注釋

                                            • 使用/** ... */進行多行注釋. 請在你們加入注釋說明,指明參數和返回值的類型

                                              // bad // make() returns a new element // based on the passed in tag name // // @param <String> tag // @return <Element> element function make(tag) { // ...stuff... return element;
                                              } // good /**  * make() returns a new element  * based on the passed in tag name  *  * @param <String> tag  * @return <Element> element  */ function make(tag) { // ...stuff... return element;
                                              }
                                              </li>

                                            • 使用//進行單行注釋. 請用一個新行來添加注釋。并在注釋行前增加一個空行。

                                              // bad var active = true; // is current tab // good // is current tab var active = true; // bad function getType() { console.log('fetching type...'); // set the default type to 'no type' var type = this._type || 'no type'; return type;
                                              } // good function getType() { console.log('fetching type...'); // set the default type to 'no type' var type = this._type || 'no type'; return type;
                                              }
                                              </li>

                                            • 如果是為了指明一個錯誤,請在你的注釋前加上FIXME或TODO前綴來幫助其他開發者快速的了解你的注釋意圖。其中FIXME可以表示這個問題需要解決,或者TODO來表示需要被實現的功能塊。

                                              </li>

                                            • 使用// FIXME:來注解一個問題。

                                              function Calculator() { // FIXME: shouldn't use a global here total = 0; return this;
                                              }
                                              </li>

                                            • 使用// TODO:來注解一個需要被實現(完成)的任務。

                                              function Calculator() { // TODO: total should be configurable by an options param this.total = 0; return this;
                                              }
                                              </li> </ul>

                                              ? back to top

                                              空格

                                              • 推薦使用2個空格作為縮進

                                                // bad function() {
                                                ????var name;
                                                } // bad function() {
                                                ?var name;
                                                } // good function() {
                                                ??var name;
                                                }
                                                </li>

                                              • 在所有起始的大括號前加一個空格

                                                // bad function test(){ console.log('test');
                                                } // good function test() { console.log('test');
                                                } // bad dog.set('attr',{
                                                  age: '1 year',
                                                  breed: 'Bernese Mountain Dog' }); // good dog.set('attr', {
                                                  age: '1 year',
                                                  breed: 'Bernese Mountain Dog' });
                                                </li>

                                              • 在操作符見使用一個空格

                                                // bad var x=y+5; // good var x = y + 5;
                                                </li>

                                              • 文件結束后增加一個空行

                                                // bad (function(global) { // ...stuff... })(this);

                                                // bad (function(global) { // ...stuff... })(this);?
                                                ?

                                                // good (function(global) { // ...stuff... })(this);?
                                                </li>

                                              • 對鏈接起來的方法使用縮進成多行的形式

                                                // bad $('#items').find('.selected').highlight().end().find('.open').updateCount(); // good $('#items')
                                                  .find('.selected')
                                                    .highlight()
                                                    .end()
                                                  .find('.open')
                                                    .updateCount(); // bad var leds = stage.selectAll('.led').data(data).enter().append('svg:svg').class('led', true)
                                                    .attr('width',  (radius + margin) * 2).append('svg:g')
                                                    .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
                                                    .call(tron.led); // good var leds = stage.selectAll('.led')
                                                    .data(data)
                                                  .enter().append('svg:svg')
                                                    .class('led', true)
                                                    .attr('width',  (radius + margin) * 2)
                                                  .append('svg:g')
                                                    .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
                                                    .call(tron.led);
                                                </li> </ul>

                                                ? back to top

                                                逗號

                                                • 推薦的做法是逗號在每一行的末尾

                                                  // bad var hero = {
                                                      firstName: 'Bob' , lastName: 'Parr' , heroName: 'Mr. Incredible' , superPower: 'strength' }; // good var hero = {
                                                    firstName: 'Bob',
                                                    lastName: 'Parr',
                                                    heroName: 'Mr. Incredible',
                                                    superPower: 'strength' };
                                                  </li>

                                                • Additional trailing comma: Nope. This can cause problems with IE6/7 and IE9 if it's in quirksmode. Also, in some implementations of ES3 would add length to an array if it had an additional trailing comma. This was clarified in ES5 (source):

                                                  Edition 5 clarifies the fact that a trailing comma at the end of an ArrayInitialiser does not add to the length of the array. This is not a semantic change from Edition 3 but some implementations may have previously misinterpreted this.

                                                  </blockquote>

                                                    // bad var hero = {
                                                      firstName: 'Kevin',
                                                      lastName: 'Flynn',
                                                    }; var heroes = [ 'Batman', 'Superman',
                                                    ]; // good var hero = {
                                                      firstName: 'Kevin',
                                                      lastName: 'Flynn' }; var heroes = [ 'Batman', 'Superman' ];
                                                  </li> </ul>

                                                  ? back to top

                                                  分號作為語句塊的結束

                                                  • Yup.

                                                    // bad (function() { var name = 'Skywalker' return name
                                                    })() // good (function() { var name = 'Skywalker'; return name;
                                                    })(); // good ;(function() { var name = 'Skywalker'; return name;
                                                    })();
                                                    </li> </ul>

                                                    ? back to top

                                                    類型轉換 & 強制類型轉換

                                                    • 在聲明語句的最前端執行強制類型轉換.
                                                    • Strings:

                                                      //  => this.reviewScore = 9; // bad var totalScore = this.reviewScore + ''; // good var totalScore = '' + this.reviewScore; // bad var totalScore = '' + this.reviewScore + ' total score'; // good var totalScore = this.reviewScore + ' total score';
                                                      </li>

                                                    • 使用parseInt來進行整數的類型轉換,并且始終提供一個基數.

                                                      var inputValue = '4'; // bad var val = new Number(inputValue); // bad var val = +inputValue; // bad var val = inputValue >> 0; // bad var val = parseInt(inputValue); // good var val = Number(inputValue); // good var val = parseInt(inputValue, 10);
                                                      </li>

                                                    • If for whatever reason you are doing something wild andparseIntis your bottleneck and need to use Bitshift for performance reasons, leave a comment explaining why and what you're doing.

                                                      // good /**  * parseInt was the reason my code was slow.  * Bitshifting the String to coerce it to a  * Number made it a lot faster.  */ var val = inputValue >> 0;
                                                      </li>

                                                    • Note: Be careful when using bitshift operations. Numbers are represented as 64-bit values, but Bitshift operations always return a 32-bit integer (source). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. Discussion. Largest signed 32-bit Int is 2,147,483,647:

                                                      2147483647 >> 0 //=> 2147483647 2147483648 >> 0 //=> -2147483648 2147483649 >> 0 //=> -2147483647
                                                      </li>

                                                    • Booleans:

                                                      var age = 0; // bad var hasAge = new Boolean(age); // good var hasAge = Boolean(age); // good var hasAge = !!age;
                                                      </li> </ul>

                                                      ? back to top

                                                      命名約定

                                                      • 避免使用當個字符命名,使用描述性的名字:

                                                        // bad function q() { // ...stuff... } // good function query() { // ..stuff.. }
                                                        </li>

                                                      • 對于對象、函數、和實例采用小駝峰(camelCase)命名法

                                                        // bad var OBJEcttsssss = {}; var this_is_my_object = {}; function c() {} var u = new user({
                                                          name: 'Bob Parr' }); // good var thisIsMyObject = {}; function thisIsMyFunction() {} var user = new User({
                                                          name: 'Bob Parr' });
                                                        </li>

                                                      • 當命名類或構造函數時使用大駝峰或Pascal命名法(PascalCase)

                                                        // bad function user(options) { this.name = options.name;
                                                        } var bad = new user({
                                                          name: 'nope' }); // good function User(options) { this.name = options.name;
                                                        } var good = new User({
                                                          name: 'yup' });
                                                        </li>

                                                      • 在私有屬性前加上一個_前綴

                                                        // bad this.__firstName__ = 'Panda'; this.firstName_ = 'Panda'; // good this._firstName = 'Panda';
                                                        </li>

                                                      • 當你要保存this值時,可以將其命名為_this.

                                                        // bad function() { var self = this; return function() { console.log(self);
                                                          };
                                                        } // bad function() { var that = this; return function() { console.log(that);
                                                          };
                                                        } // good function() { var _this = this; return function() { console.log(_this);
                                                          };
                                                        }
                                                        </li>

                                                      • 命名你的函數。這將有助于堆棧跟蹤。

                                                        // bad var log = function(msg) { console.log(msg);
                                                        }; // good var log = function log(msg) { console.log(msg);
                                                        };
                                                        </li> </ul>

                                                        ? back to top

                                                        訪問器

                                                        • 屬性訪問器并不是必須的。
                                                        • 如果你確實需要,請命名為 getVal() 和 setVal('hello') 的形式

                                                          // bad dragon.age(); // good dragon.getAge(); // bad dragon.age(25); // good dragon.setAge(25);
                                                          </li>

                                                        • 如果屬性是一個布爾值,請使用 isVal() 或 hasVal()

                                                          // bad if (!dragon.age()) { return false;
                                                          } // good if (!dragon.hasAge()) { return false;
                                                          }
                                                          </li>

                                                        • 你也可以創建 get() 和 set() 函數, 但一定要保持一致.

                                                          function Jedi(options) {
                                                            options || (options = {}); var lightsaber = options.lightsaber || 'blue'; this.set('lightsaber', lightsaber);
                                                          } Jedi.prototype.set = function(key, val) { this[key] = val;
                                                          }; Jedi.prototype.get = function(key) { return this[key];
                                                          };
                                                          </li> </ul>

                                                          ? back to top

                                                          構造函數

                                                          • 在原型鏈上增加屬性,而不是覆寫原型鏈。

                                                            function Jedi() { console.log('new jedi');
                                                            } // bad Jedi.prototype = { fight: function fight() { console.log('fighting');
                                                              }, block: function block() { console.log('blocking');
                                                              }
                                                            }; // good Jedi.prototype.fight = function fight() { console.log('fighting');
                                                            }; Jedi.prototype.block = function block() { console.log('blocking');
                                                            };
                                                            </li>

                                                          • 你可以在方法中返回this從而來構建可鏈接的方法。

                                                            // bad Jedi.prototype.jump = function() { this.jumping = true; return true;
                                                            }; Jedi.prototype.setHeight = function(height) { this.height = height;
                                                            }; var luke = new Jedi();
                                                            luke.jump(); // => true luke.setHeight(20) // => undefined // good Jedi.prototype.jump = function() { this.jumping = true; return this;
                                                            }; Jedi.prototype.setHeight = function(height) { this.height = height; return this;
                                                            }; var luke = new Jedi();

                                                            luke.jump() .setHeight(20);</pre></div> </li>

                                                          • 你可以創建一個自定義的toString()方法,但是你要確保它能正常工作并且沒有其他副作用。

                                                            function Jedi(options) {
                                                              options || (options = {}); this.name = options.name || 'no name';
                                                            } Jedi.prototype.getName = function getName() { return this.name;
                                                            }; Jedi.prototype.toString = function toString() { return 'Jedi - ' + this.getName();
                                                            };
                                                            </li> </ul>

                                                            ? back to top

                                                            ES6箭頭函數

                                                            • 所有的Arrow Function的參數均使用()包裹,即便只有一個參數:

                                                              // good let foo = (x) => x + 1; // bad let foo = x => x + 1;
                                                              </li>

                                                            • 定義函數盡量使用Arrow functions,而不是function關鍵字

                                                              // good let foo = () => { // code  }; // bad function foo() { // code  } // bad let foo = function () { // code  }

                                                              除非當前場景不適合使用Arrow Function,如函數表達式需要自遞歸、需要運行時可變的this對象等。

                                                              </li>

                                                            • 對于對象、類中的方法,使用增強的對象字面量

                                                              // good let foo = { bar () { // code  }
                                                              } // bad let foo = {
                                                                bar: () => { // code  }
                                                              } // bad let foo = { bar: function () { // code }
                                                              }
                                                              </li> </ul>

                                                              ES6增強的對象字面量

                                                              • 可以在對象總直接定義方法

                                                                // good let foo = { bar() { // code  }
                                                                }
                                                                </li>

                                                              • 可使用通過計算得出的鍵值

                                                                // 當你需要的時候使用 let MY_KEY = 'bar'; let foo = {
                                                                  [MY_KEY + 'Hash']: 123 }
                                                                </li>

                                                              • 與當前scope中同名變量的簡寫

                                                                // bad let bar = 'bar'; let foo = {
                                                                    bar // 相當于bar: bar };
                                                                </li> </ul>

                                                                ES6模板字符串

                                                                • 不推薦使用多行字符串,因為不方便代碼縮進

                                                                  // bad let html = `<div>  <p>Hello world</p> </div>`
                                                                  </li>

                                                                • 推薦使用ES6的字符串變量替換功能,這樣可以取代字符串拼接

                                                                  //good let name = 'weiwei'; let time = '22:00'; let message = `Hello ${name}, it's ${time} now`;
                                                                  </li> </ul>

                                                                  ES6函數參數增強

                                                                  • 推薦使用默認值、剩余參數等功能,這能讓你的函數聲明和調用變得更為簡潔

                                                                    var foo = (x = 1) => x + 1;
                                                                    foo(); // 2 var extend = (source, ...args) => { for (let target in args) { for (let name in Object.keys(target) { if (!source.hasOwnProperty(name) {
                                                                                    source[name] = target[name];
                                                                                }
                                                                            }
                                                                        }
                                                                    }; var extensions = [
                                                                        {name: 'Zhang'},
                                                                        {age: 17},
                                                                        {work: 'hard'}
                                                                    ];
                                                                    extend({}, ...extensions);
                                                                    </li> </ul>

                                                                    ES6新增關鍵字let和const