1.let 取代 var;
2.在let和const之间,建议优先使用const,尤其是在全局环境,不应该设置变量,只应设置常量;
3.静态字符串一律使用单引号或反引号,不使用双引号。动态字符串使用反引号;
4.使用数组成员对变量赋值时,优先使用解构赋值;
5.单行定义的对象,最后一个成员不以逗号结尾。多行定义的对象,最后一个成员以逗号结尾;
6.使用扩展运算符(…)拷贝数组;使用 Array.from 方法,将类似数组的对象转为数组;
7.立即执行函数可以写成箭头函数的形式:
(() => {
console.log('Welcome to the Internet.');
})();
8.那些需要使用函数表达式的场合,尽量用箭头函数代替。因为这样更简洁,而且绑定了 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);
9.使用默认值语法设置函数参数的默认值:
// bad
function handleThings(opts) {
opts = opts || {};
}
// good
function handleThings(opts = {}) {
// ...
}
10.总是用 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;
}
}
11.使用extends实现继承,因为这样更简单,不会有破坏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];
}
}
12.Module 语法是 JavaScript 模块的标准写法,坚持使用这种写法。使用import取代require:
// bad
const moduleA = require('moduleA');
const func1 = moduleA.func1;
const func2 = moduleA.func2;
// good
import { func1, func2 } from 'moduleA';
13.使用export取代module.exports:
// commonJS的写法
var React = require('react');
var Breadcrumbs = React.createClass({
render() {
return <nav />;
}
});
module.exports = Breadcrumbs;
// ES6的写法
import React from 'react';
class Breadcrumbs extends React.Component {
render() {
return <nav />;
}
};
export default Breadcrumbs;
14.不要在模块输入中使用通配符。因为这样可以确保你的模块之中,有一个默认输出(export default):
// bad
import * as myObject from './importModule';
// good
import myObject from './importModule';
15.如果模块默认输出一个函数,函数名的首字母应该小写:
function makeStyleGuide() {
}
export default makeStyleGuide;
16.如果模块默认输出一个对象,对象名的首字母应该大写:
const StyleGuide = {
es6: {
}
};
export default StyleGuide;