本规范提供了一种统一的编码规范来编写ES6代码;
提升代码可读性
//bad
import ElementUI from 'element-ui'
let a = 2
let b = 3
//good
import ElementUI from 'element-ui';
let a = 2;
let b = 3;
// bad
var a = 1;
var b = 2;
// good
const a = 1;
const b = 2;
因为 let 是块级作用域,而 var 是函数作用域。
// bad
var count = 1;
if (true) {
count += 1;
}
// good, use the let.
let count = 1;
if (true) {
count += 1;
}
// bad
const item = new Object();
// good
const item = {};
// bad
const atom = {
value: 1,
addValue: function (value) {
return atom.value + value;
},
};
// good
const atom = {
value: 1,
addValue(value) {
return atom.value + value;
},
};
这样更短更有描述性。
const lukeSkywalker = 'Luke Skywalker';
// bad
const obj = {
lukeSkywalker: lukeSkywalker,
};
// good
const obj = {
lukeSkywalker,
};
// bad
console.log(object.hasOwnProperty(key));
// good
console.log(Object.prototype.hasOwnProperty.call(object, key));
// best
const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
/* or */
const has = require('has');
…
console.log(has.call(object, key));
// very bad
const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); // this mutates `original`
delete copy.a; // so does this
// bad
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }
// good
const original = { a: 1, b: 2 };
const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }
const { a, ...noA } = copy; // noA => { b: 2, c: 3 }
虽然 Vue.js 支持传递复杂的 JavaScript 对象通过 props 属性,但是你应该尽可能的使用原始类型的数据。尽量只使用 JavaScript 原始类型(字符串、数字、布尔值)和函数。尽量避免复杂的对象。
// bad
const items = new Array();
// good
const items = [];
// bad
const items = new Array();
// good
const items = [];
// bad
const len = items.length;
const itemsCopy = [];
let i;
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
// good
const itemsCopy = [...items]
const foo = document.querySelectorAll('.foo');
const nodes = Array.from(foo);
为什么?因为函数声明是可命名的,所以他们在调用栈中更容易被识别。此外,函数声明会把整个函数提升(hoisted),而函数表达式只会把函数的引用变量名提升。这条规则使得箭头函数可以取代函数表达式。
// bad
const foo = function () {
};
// good
function foo() {
}
// 立即调用的函数表达式 (IIFE)
(() => {
console.log('Welcome to the Internet. Please follow me.');
})();
// bad
if (currentUser) {
function test() {
console.log('Nope.');
}
}
// good
let test;
if (currentUser) {
test = () => {
console.log('Yup.');
};
}
为什么?使用 … 能明确你要传入的参数。另外 rest 参数是一个真正的数组,而 arguments 是一个类数组。
// bad
function concatenateAll() {
const args = Array.prototype.slice.call(arguments);
return args.join('');
}
// good
function concatenateAll(...args) {
return args.join('');
}
按照一定的结构组织,使得组件便于理解。
为什么?因为箭头函数创造了新的一个 this 执行环境(译注:参考 Arrow functions - JavaScript | MDN 和 ES6 arrow functions, syntax and lexical scoping),通常情况下都能满足你的需求,而且这样的写法更为简洁。
为什么不?如果你有一个相当复杂的函数,你或许可以把逻辑部分转移到一个函数声明上。
// bad
[1, 2, 3].map(function (x) {
return x * x;
});
// good
[1, 2, 3].map((x) => {
return x * x;
});
为什么?语法糖。在链式调用中可读性很高。 为什么不?当你打算回传一个对象的时候。
// good
[1, 2, 3].map(x => x * x);
// good
[1, 2, 3].reduce((total, n) => {
return total + n;
}, 0);
为什么? 因为 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;
}
}
为什么?因为 extends 是一个内建的原型继承方法并且不会破坏 instanceof。
而不是其他非标准模块系统。你可以编译为你喜欢的模块系统。 为什么?模块就是未来,让我们开始迈向未来吧。
为什么?这样能确保你只有一个默认 export。
// bad
import * as AirbnbStyleGuide from './AirbnbStyleGuide';
// good
import AirbnbStyleGuide from './AirbnbStyleGuide';
为什么?虽然一行代码简洁明了,但让 import 和 export 各司其职让事情能保持一致。
// bad
// filename es6.js
export { es6 as default } from './airbnbStyleGuide';
// good
// filename es6.js
import { es6 } from './AirbnbStyleGuide';
export default es6;
如果不这样做就会产生全局变量。我们需要避免全局命名空间的污染。
// bad
superPower = new SuperPower();
// good
const superPower = new SuperPower();
为什么?增加新变量将变的更加容易,而且你永远不用再担心调换错。
为什么?当你需要把已赋值变量赋值给未赋值变量时非常有用。
// bad
let i, len, dragonball,
items = getItems(),
goSportsTeam = true;
// bad
let i;
const items = getItems();
let dragonball;
const goSportsTeam = true;
let len;
// good
const goSportsTeam = true;
const items = getItems();
let dragonball;
let i;
let length;
为什么?let 和 const 是块级作用域而不是函数作用域。
let 和 const 被赋予了一种称为「暂时性死区(Temporal Dead Zones, TDZ)」的概念。这对于了解为什么 type of 不再安全相当重要。
.对象 被计算为 true .Undefined 被计算为 false .Null 被计算为 false .布尔值 被计算为 布尔的值 .数字 如果是 +0、-0、或 NaN 被计算为 false, 否则为 true .字符串 如果是空字符串 ” 被计算为 false,否则为 true
// 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;
}
帮助其他开发者快速了解这是一个需要复查的问题,或是给需要实现的功能提供一个解决方式。这将有别于常见的注释,因为它们是可操作的。使用 FIXME – need to figure this out 或者 TODO – need to implement。
class Calculator {
constructor() {
// FIXME: shouldn't use a global here
total = 0;
}
}
class Calculator {
constructor() {
// TODO: total should be configurable by an options param
this.total = 0;
}
}
在函数调用及声明中,不在函数的参数列表前加空格。