Airbnb 出品,目前非常流行的 JavaScript 代码规范(中文版)。其内对各种 js 范式的写法进行了详细的规定与说明,按照此规范写出的代码将会更加合理。
Airbnb 出品,目前非常流行的 JavaScript 代码规范(中文版)。其内对各种 js 范式的写法进行了详细的规定与说明,按照此规范写出的代码将会更加合理。
一种写JavaScript更合理的代码风格。
Note: 本指南假设你使用了 Babel, 并且要求你使用 babel-preset-airbnb 或者其他同等资源。 并且假设你在你的应用中安装了 shims/polyfills ,使用airbnb-browser-shims 或者相同功能。 其他代码风格指南
1.1 原始值: 当你访问一个原始类型的时候,你可以直接使用它的值。
stringnumberbooleannullundefinedsymbolconst foo = 1;
let bar = foo;
bar = 9;
console.log(foo, bar); // => 1, 91.2 复杂类型: 当你访问一个复杂类型的时候,你需要一个值得引用。
objectarrayfunctionconst foo = [1, 2];
const bar = foo;
bar[0] = 9;
console.log(foo[0], bar[0]); // => 9, 92.1 使用 const 定义你的所有引用;避免使用 var。 eslint: prefer-const, no-const-assign
为什么? 这样能够确保你不能重新赋值你的引用,否则可能导致错误或者产生难以理解的代码。.
// bad
var a = 1;
var b = 2;
// good
const a = 1;
const b = 2;2.2 如果你必须重新赋值你的引用, 使用 let 代替 var。 eslint: no-var
为什么?
let是块级作用域,而不像var是函数作用域.
// bad
var count = 1;
if (true) {
count += 1;
}
// good, use the let.
let count = 1;
if (true) {
count += 1;
}2.3 注意,let 和 const 都是块级范围的。
// const 和 let 只存在于他们定义的块中。
{
let a = 1;
const b = 1;
}
console.log(a); // ReferenceError
console.log(b); // ReferenceError3.1 使用字面语法来创建对象。 eslint: no-new-object
// bad
const item = new Object();
// good
const item = {};3.2 在创建具有动态属性名称的对象时使用计算属性名。
为什么? 它允许你在一个地方定义对象的所有属性。
function getKey(k) {
return `a key named ${k}`;
}
// bad
const obj = {
id: 5,
name: 'San Francisco',
};
obj[getKey('enabled')] = true;
// good
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true,
};3.3 使用对象方法的缩写。 eslint: object-shorthand
// bad
const atom = {
value: 1,
addValue: function (value) {
return atom.value + value;
},
};
// good
const atom = {
value: 1,
addValue(value) {
return atom.value + value;
},
};3.4 使用属性值的缩写。 eslint: object-shorthand
为什么? 它的写法和描述较短。
const lukeSkywalker = 'Luke Skywalker';
// bad
const obj = {
lukeSkywalker: lukeSkywalker,
};
// good
const obj = {
lukeSkywalker,
};3.5 在对象声明的时候将简写的属性进行分组。
为什么? 这样更容易的判断哪些属性使用的简写。
const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';
// bad
const obj = {
episodeOne: 1,
twoJediWalkIntoACantina: 2,
lukeSkywalker,
episodeThree: 3,
mayTheFourth: 4,
anakinSkywalker,
};
// good
const obj = {
lukeSkywalker,
anakinSkywalker,
episodeOne: 1,
twoJediWalkIntoACantina: 2,
episodeThree: 3,
mayTheFourth: 4,
};3.6 只使用引号标注无效标识符的属性。 eslint: quote-props
为什么? 总的来说,我们认为这样更容易阅读。 它提升了语法高亮显示,并且更容易通过许多 JS 引擎优化。
// bad
const bad = {
'foo': 3,
'bar': 4,
'data-blah': 5,
};
// good
const good = {
foo: 3,
bar: 4,
'data-blah': 5,
};3.7 不能直接调用 Object.prototype 的方法,如: hasOwnProperty 、 propertyIsEnumerable 和 isPrototypeOf。
为什么? 这些方法可能被以下问题对象的属性追踪 - 相应的有
{ hasOwnProperty: false }- 或者,对象是一个空对象 (Object.create(null))。
// bad
console.log(object.hasOwnProperty(key));
// good
console.log(Object.prototype.hasOwnProperty.call(object, key));
// best
const has = Object.prototype.hasOwnProperty; // 在模块范围内的缓存中查找一次
/* or */
import has from 'has'; // https://www.npmjs.com/package/has
// ...
console.log(has.call(object, key));3.8 更喜欢对象扩展操作符,而不是用 Object.assign 浅拷贝一个对象。 使用对象的 rest 操作符来获得一个具有某些属性的新对象。
// very bad
const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); // 变异的 `original` ಠ_ಠ
delete copy.a; // 这....
// 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 }4.1 使用字面语法创建数组。 eslint: no-array-constructor
// bad
const items = new Array();
// good
const items = [];4.2 使用 Array#push 取代直接赋值来给数组添加项。
const someStack = [];
// bad
someStack[someStack.length] = 'abracadabra';
// good
someStack.push('abracadabra');4.3 使用数组展开方法 ... 来拷贝数组。
// bad
const len = items.length;
const itemsCopy = [];
let i;
for (i = 0; i < len; i += 1) {
itemsCopy[i] = items[i];
}
// good
const itemsCopy = [...items];4.4 将一个类数组对象转换成一个数组, 使用展开方法 ... 代替 Array.from。
const foo = document.querySelectorAll('.foo');
// good
const nodes = Array.from(foo);
// best
const nodes = [...foo];4.5 对于对迭代器的映射,使用 Array.from 替代展开方法 ... , 因为它避免了创建中间数组。
// bad
const baz = [...foo].map(bar);
// good
const baz = Array.from(foo, bar);array-callback-return…4.7 如果数组有多行,则在开始的时候换行,然后在结束的时候换行。
// bad
const arr = [
[0, 1], [2, 3], [4, 5],
];
const objectInArray = [{
id: 1,
}, {
id: 2,
}];
const numberInArray = [
1, 2,
];
// good
const arr = [[0, 1], [2, 3], [4, 5]];
const objectInArray = [
{
id: 1,
},
{
id: 2,
},
];
const numberInArray = [
1,
2,
];5.1 在访问和使用对象的多个属性的时候使用对象的解构。 eslint: prefer-destructuring
为什么? 解构可以避免为这些属性创建临时引用。
// bad
function getFullName(user) {
const firstName = user.firstName;
const lastName = user.lastName;
return `${firstName} ${lastName}`;
}
// good
function getFullName(user) {
const { firstName, lastName } = user;
return `${firstName} ${lastName}`;
}
// best
function getFullName({ firstName, lastName }) {
return `${firstName} ${lastName}`;
}5.2 使用数组解构。 eslint: prefer-destructuring
const arr = [1, 2, 3, 4];
// bad
const first = arr[0];
const second = arr[1];
// good
const [first, second] = arr;5.3 对于多个返回值使用对象解构,而不是数组解构。
为什么? 你可以随时添加新的属性或者改变属性的顺序,而不用修改调用方。
// bad
function processInput(input) {
// 处理代码...
return [left, right, top, bottom];
}
// 调用者需要考虑返回数据的顺序。
const [left, __, top] = processInput(input);
// good
function processInput(input) {
// 处理代码...
return { left, right, top, bottom };
}
// 调用者只选择他们需要的数据。
const { left, top } = processInput(input);No open issues yet, or sync has not completed.