JavaScript 的流行主义风格
一种(一日)自动更新的风格,取而代之的是人民,只有 人类.
今天,这仍然是一套规则。 一定要有目标,不是吗? 副本
遗憾的是,与最新数据相比,以下数据有些过时 eslint 规则
内 index.js。它们仍然存在,因为很可能重用英文副本
即使有新的和/或略有不同的规则.
如果您对此有评论或 规则有分歧 接下来 请直接联系我 我想听这个!
目录
基本情况
标识符和初始符
发言和技术
遵约水平
不错和坏
- 总是/必须: 这是 强制。 。 。 . 说真的
- 永远不能曰别 永远 做到这一点。 说真的.
- 应数字 : 试着 做到这一点。 它受到鼓励,但没有严格执行.
- 不应该数字 : 尽量不要 做到这一点。 这是令人沮丧的,但并不禁止.
基本规则
- 欧盟驻科法治团数字 : 永远 2-空格软缩进( 无标签)
- 欧盟驻科法治团数字 : 永远 分号(与 一个例外) (中文(简体) ).
- 欧盟驻科法治团数字 : 不要先用逗号
- 欧盟驻科法治团数字 : 永远不要使用
()周围的发言,像typeof或者说delete。 。 。 .
分号
- 欧盟驻科法治团: 分号
;必须 在每个发言的结尾处添加, 除外 当下一个字符为收尾括号时}在这种情况下,可以省略.
//
// GOOD
//
var f = function add(a, b) {
if (a == b) { return a * 2 } // No `;` here.
return a + b;
};
//
// BAD
//
var f = function add (a, b) {
return a + b
}
括号
- 欧盟驻科法治团括号 必须 用于所有情况。 他们 可能 用于围绕简单语句的一行.
//
// GOOD
//
if (x) { return true }
//
// BAD
//
if (x)
while (1)
i ++;
else
//...
//
// BAD
//
if (x) return true;
//
// BAD
//
if (x)
return true;
- 欧盟驻科法治团: 打开括号 绝对不能 在他们自己的线.
- 规则: 关闭牙套 绝对不能 之后是有条件声明
垂直屏幕空间是珍贵的,而且扫描代码容易 更前一个.
//
// GOOD
//
if (x) {
return true;
}
else {
return false;
}
//
// BAD
//
if (x)
{
return true;
}
//
// BAD
//
if (x) {
return true; }
//
// BAD
//
if (x) {
return true;
} else {
return false
}
- 欧盟驻科法治团: 关闭括号 必须永远 除非他们也从这条线上开始 否则就自己上.
这样很容易看到一个函数或语句的结束
//
// GOOD
//
return callback && callback({ foo: bar });
//
// GOOD
//
return callback && callback({
foo: bar
});
//
// BAD
//
return callback && callback({
foo: bar });
//
// BAD
//
return callback && callback({ foo: bar
});
命名公约
- 欧盟驻科法治团: 避免单字母名称. 用你的命名来形容.
//
// BAD
//
function q() {
// ...stuff...
}
//
// GOOD
//
function query() {
// ..stuff..
}
- 欧盟驻科法治团: 命名对象、函数和实例时使用骆驼Case
//
// BAD
//
var OBJEcttsssss = {};
var this_is_my_object = {};
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'
});
- 欧盟驻科法治团: 在命名构建器或类时使用 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'
});
- 欧盟驻科法治团: 使用主下划线
_指定私有属性时
// BAD
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
// GOOD
this._firstName = 'Panda';
- 欧盟驻科法治团: 已保存参考文献
this(这是一个原生物体) 必须 使用情况self。 。 。 .
function User (options) {
this.setup();
}
//
// GOOD
//
User.prototype.setup = function () {
var self = this;
setTimeout(function () {
self.ready = true
}, 1000);
};
//
// BAD
//
User.prototype.setup = function () {
var that = this;
setTimeout(function () {
that.ready = true
}, 1000);
};
- 欧盟驻科法治团: 已保存参考文献
this(这是一个任意的范围) 应 使用情况that。 。 。 .
//
// BAD
//
function () {
var self = this;
return function() {
console.log(self);
};
}
//
// BAD
//
function () {
var _this = this;
return function() {
console.log(_this);
};
}
//
// GOOD
//
function () {
var that = this;
return function() {
console.log(that);
};
}
- 欧盟驻科法治团: 函数 应 名称。 这对堆放痕迹很有帮助.
//
// OK
//
var log = function(msg) {
console.log(msg);
};
//
// GOOD
//
var log = function log(msg) {
console.log(msg);
};
可变声明
- 欧盟驻科法治团: 变量 必须 总是在使用前宣布.
- 欧盟驻科法治团: 可变声明 必须 ,而不是在其他块内。 例外的是 页:1 循环.
可变声明移动到函数的顶端 不管怎么说,这就是他们属于的地方.
//
// GOOD
//
function (a, b) {
var k;
if (a == b) {
k = true;
}
//...
}
for (var i = 0; i < l; i ++) {
//...
}
//
// BAD
//
function (a, b) {
if (a == b) {
var k = true;
}
//...
}
- 欧盟驻科法治团: 变量 必须 当它们被宣布时总是对齐
这使得可以很容易地扫描一个块中申报的内容.
//
// GOOD
//
var bazz,
foo,
bar;
//
// BAD
//
var bazz,
foo,
bar;
- 欧盟驻科法治团: 宣布最后一个未指定变量.
当您稍后需要根据之前指定的变量之一指定变量时, 这样做很有帮助 .
//
// BAD
//
var i, len, dragonball,
items = getItems(),
goSportsTeam = true;
//
// BAD
//
var i, items = getItems(),
dragonball,
goSportsTeam = true,
len;
//
// GOOD
//
var items = getItems(),
goSportsTeam = true,
dragonball,
length,
i;
- 欧盟驻科法治团: 变量 应 总是以逐渐减少的长度宣布.
这也使得扫描一个区块中申报的内容更容易(相信我).
//
// GOOD
//
var reallyLongVar,
shorterVar,
fooBar,
foo;
//
// BAD
//
var fooBar,
shorterVar,
foo,
reallyLongVar;
- 欧盟驻科法治团: 可变任务 必须 在声明前来.
- 欧盟驻科法治团: 可变任务 应 对齐 方便的时候 取决于额外长度.
这也使得扫描一个区块中申报的内容更容易(相信我).
//
// GOOD
//
var reallyLongVar = 10e3,
shorterVar = 5e2,
fooBar = 'foobar',
foo;
//
// OK
//
var reallyLongVar = 10e3,
shorterVar = 5e2,
fooBar = 'foobar',
foo;
//
// BAD
//
var foo,
reallyLongVar = 10e3,
shorterVar = 5e2,
fooBar = 'foobar';
- 欧盟驻科法治团: 多行对象文字 必须是 在多行变量声明块之外指定.
这是神会想要的.
//
// GOOD
//
var obj = { list: [], expired: false },
bazz = 100,
foo,
bar;
//
// GOOD
//
var bazz = 100,
foo,
bar,
obj;
obj = {
list: [],
expired: false
};
//
// BAD
//
var obj = {
list: [],
expired: false
},
bazz = 100,
foo,
bar;
//
// BAD
//
var bazz = 100,
foo,
bar,
obj = {
list: [],
expired: false
};
- 欧盟驻科法治团: 根据多行函数或多功能进行分配 必须是 在多行变量声明块之外指定.
//
// GOOD
//
var memo = list.filter(function (i) { return i < 10 }),
bazz = 100,
foo,
bar;
//
// GOOD
//
var bazz = 100,
memo,
foo,
bar;
memo = list.filter(function (i) {
return i < 10;
}).filter(Boolean);
//
// BAD
//
var memo = list.filter(function (i) {
return i < 10
}),
bazz = 100,
foo,
bar;
//
// BAD
//
var bazz = 100,
foo,
bar,
memo = list.filter(function (i) {
return i < 10;
}).filter(Boolean);
//
// BAD
//
var bazz = 100,
foo,
bar,
memo = list.filter(function (i) { return i < 10 })
.filter(Boolean);
对象
- 欧盟驻科法治团: 单行对象 必须 后面有一个后端空间
{和一个前导空间}。 。 。 .
//
// BAD
//
var foo = {bar: 1};
//
// BAD
//
return {bar: 1};
//
// GOOD
//
var foo = { bar: 1 };
//
// GOOD
//
return { bar: 1 };
- 欧盟驻科法治团: 对象中的属性 必须 之后是a
:
//
// BAD
//
var foo = { bar:1 };
//
// BAD
//
var foo = {
bar : 1,
bazz : 1
};
//
// GOOD
//
var foo = { bar: 1 };
//
// GOOD
//
var foo = {
bar: 1,
bazz: 1
};
//
// GOOD
//
var foo = {
bar: 1,
bazz: 1
};
- 欧盟驻科法治团: 多行任务说明 对象文字内 为: 鼓励.
减少管理的变量数量,对象创建费用低廉.
//
// GOOD
//
return {
foos: list.filter(function (i) {
return i.type === 'foo';
}),
bars: list.filter(function (i) {
return i.type === 'bar';
})
}
- 欧盟驻科法治团:使用字面语法来创建对象.
//
// BAD
//
var item = new Object();
//
// GOOD
//
var item = {};
- 使用 保留词 没问题 这是有效的 Javascript.
//
// OK
//
var superman = {
class: 'superhero',
default: { clark: 'kent' },
private: true
};
阵列
- 欧盟驻科法治团: 使用字面语法创建数组
//
// BAD
//
var items = new Array();
// GOOD
var items = [];
- 欧盟驻科法治团: 如果您不知道阵列长度, 请使用 Array# push .
var someStack = [];
//
// BAD
//
someStack[someStack.length] = 'abracadabra';
//
// GOOD
//
someStack.push('abracadabra');
- 欧盟驻科法治团: 当您需要复制一个阵列时, 使用 Array# slice . jsperf 软件
var len = items.length,
itemsCopy = [],
i;
//
// BAD
//
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
//
// GOOD
//
itemsCopy = items.slice();
字符串
- 欧盟驻科法治团: 使用单引号
''用于字符串
//
// BAD
//
var name = "Bob Parr";
//
// GOOD
//
var name = 'Bob Parr';
//
// BAD
//
var fullName = "Bob " + this.lastName;
//
// GOOD
//
var fullName = 'Bob ' + this.lastName;
- 欧盟驻科法治团:字符串长于80个字符,应当使用字符串协和来跨多行写出.
//
// 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 = [
'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.'
].join(' ');
- 欧盟驻科法治团:在编程上建立字符串时,使用Array#join来代替字符串连接. 主要用于IE: jsperf 软件。 。 。 .
var items,
messages,
length,
i;
messages = [{
state: 'success',
message: 'This one worked.'
}, {
state: 'success',
message: 'This one worked as well.'
}, {
state: 'error',
message: 'This one did not work.'
}];
length = messages.length;
//
// BAD
//
function inbox(messages) {
items = '<ul>';
for (i = 0; i < length; i++) {
items += '<li>' + messages[i].message + '</li>';
}
return items + '</ul>';
}
//
// GOOD
//
function inbox(messages) {
items = [];
for (i = 0; i < length; i++) {
items[i] = messages[i].message;
}
return '<ul><li>' + items.join('</li><li>') + '</li></ul>';
}
代码注释
- 欧盟驻科法治团时间轴: 不应该 请使用JSDoc.
- 欧盟驻科法治团: 块注释 只应 用于文件头.
- 欧盟驻科法治团时间轴: 不应该 使用单行块注释
- 欧盟驻科法治团:在评论前放出一行空行.
在代码注释中留有适当的空格会写 复杂代码更容易读取。 这是"几乎识字的编码" 办法.
- 复语: 应考虑联合来文文件 堕地. 当有时间改进
docco-我们用过一些有风格的评论... ...我们会一起取代它.
不错
/*
* a-js-file.js: This is some file
*
* (C) 2013 Whomever
* MIT LICENSE
*
*/
//
// ### function myFunction (a, b, c)
// #### @a {string} A variable
// #### @b {boolean} Another variable
// #### @c {object|Array} An object or an array
//
// This is the description to my function.
//
//
// Adding additional padding in your code comments
//
var a = 0;
//
// Along with additional whitespace
//
if (!a) {
console.log('Makes your code easier to read.');
console.log('What are you running out of bytes?');
}
// One line comments
var a = 0;
// and no whitespace
if (!a) {
console.log('make your code harder to read');
console.log('seriously.');
}
/*
* I'm using block comments anywhere but the file header.
*/
- 欧盟驻科法治团: 使用
// FIXME:来说明问题. - 欧盟驻科法治团: 使用
// TODO:说明解决问题的办法. - 欧盟驻科法治团: 使用
// REMARK:说明可能的说明或公开的执行问题(这些问题并非明显问题). - 欧盟驻科法治团: 用您的 Github 用户名签名这些注释 .
不错
function Calculator() {
// FIXME (index zero): shouldn't use a global here
total = 0;
return this;
}
function Calculator() {
// TODO (indexzero): total should be configurable by an options param
this.total = 0;
return this;
}
坏东西
function Calculator() {
// shouldn't use a global here
total = 0;
return this;
}
function Calculator() {
// TODO: total should be configurable by an options param
this.total = 0;
return this;
}
构造器
- 欧盟驻科法治团:向原型物体指定方法. 你个 绝对不能 用新对象完全覆盖原型.
覆写原型使得继承变得不可能:通过重置原型,你就能覆写地基!
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');
};
- 欧盟驻科法治团: 方法可以返回
this帮助方法链.
//
// OK
//
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);
- 欧盟驻科法治团: 写自定义到String()方法没关系, 只要确保它成功运作, 并且不会引起副作用.
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();
};
控制流量
- 欧盟驻科法治团: 控制流程语句, 如
if, (中文(简体) ),while财务报告和审定财务报表for必须 在关键词和左括号之间有一个空格.
它们不是功能, 因此更好的区分像这样.
//
// GOOD
//
if (a) {
return true;
}
//
// BAD
//
if(a) {
return true;
}
- 欧盟驻科法治团: Eager 返回时 必须是 首选项
if else块.
Eager返回简化了大多数控制流,尤其是更复杂和高水平的控制流.
//
// BAD
//
if (foo) {
callback(null, 'foo');
}
else {
callback(null, 'bar');
}
//
// GOOD
//
if (foo) {
return callback(null, 'foo');
}
callback(null, 'bar');
职能
- 欧盟驻科法治团: 匿名函数 必须 在
function关键词和左括号.
强调缺乏识别特征,并将其与指定职能区分开来.
//
// GOOD
//
function (a, b) {}
//
// BAD
//
function(a, b) {}
- 欧盟驻科法治团: 已命名函数 绝对不能 在函数名称和左括号之间有一个空格.
- 欧盟驻科法治团: 函数调用 绝对不能 在函数名称和左括号之间有一个空格.
//
// GOOD
//
function add(a, b) {}
//
// BAD
//
function add (a, b) {}
条件
- 欧盟驻科法治团: 多行有条件声明 必须 适当缩进.
- 欧盟驻科法治团: 多行条件语句中的新行 必须 后面是布尔运算符或
(。 。 。 . - 欧盟驻科法治团: 有条件 不应该 包含复杂的逻辑.
//
// GOOD
//
if (something === 'foo' && (somethingElse === 'bar'
&& ohYeahThisToo === 'bazz')) {
return false;
}
//
// BAD
//
if (something === 'foo' && (somethingElse === 'bar' &&
ohYeahThisToo === 'bazz')) {
return false;
}
//
// BAD
//
if (something === 'foo' && (somethingElse === 'bar' &&
ohYeahThisToo === 'bazz') {
return false;
}
//
// OK
//
if (list.filter(function (i) { return i.ok }).length > 5) {
return false;
}
铸造和胁迫类型
- 欧盟驻科法治团:在声明开头处进行类型强制.
// => 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';
- 欧盟驻科法治团: 使用
parseInt用于数字,并始终带有用于类型铸造的弧度.
如果你出于某种原因 做了一些疯狂的事
parseInt你的瓶颈和需要 切换到 业绩原因留言解释原因和行为.
数字
var inputValue = '4';
//
// OK
//
var val = +inputValue;
//
// BAD
//
var val = new Number(inputValue);
//
// BAD
//
var val = inputValue >> 0;
//
// BAD
//
var val = parseInt(inputValue);
//
// GOOD
//
var val = Number(inputValue);
//
// GOOD
//
var val = parseInt(inputValue, 10);
//
// 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;
布尔
var age = 0;
//
// BAD
//
var hasAge = new Boolean(age);
//
// GOOD
//
var hasAge = Boolean(age);
//
// GOOD
//
var hasAge = !!age;
三级操作员
- 欧盟驻科法治团: 三进制操作员没事,但是 永远不能合并。 。 。 .
不止一个,是意大利面.
//
// GOOD
//
var i = 2,
x = i > 5 ? i : 0;
//
// BAD
//
var i = 2,
j = 3,
x = i > 5 ? j > 4 ? j : i : 0;
- 欧盟驻科法治团: 多线三联运算符是好的, 但是 必须是单行语句.。 。 。 .
//
// GOOD
//
return foo
? foo + 1
: bar;
//
// GOOD
//
return foo ? foo + 1 : bar;
//
// GOOD
//
return foo
? function () { return foo + 1 }
: bar;
//
// GOOD
//
return err
? callback(err)
: callback();
//
// BAD
//
return foo ?
foo + 1 :
bar;
//
// BAD
//
return foo
? foo + 1 :
bar;
//
// BAD
//
return foo
? function (wtf) {
return foo + 1; // No multi-line return values!
}
: bar;
- 欧盟驻科法治团: 三级操作员与
return应该是 首选项if (err) { return }块.
//
// OK
//
if (err) {
return callback(err);
}
callback();
//
// GOOD
//
return err
? callback(err)
: callback();
错误
- 欧盟驻科法治团时间轴: 必须永远 扔出或返回错误. 字符串不是错误。 。 。 .
如果您想要更多描述错误, 请使用 错误。 。 。 .
//
// GOOD
//
throw new Error('I have a call-stack and other good things.');
//
// GOOD
//
callback(new Error('I have a call-stack and other good things.'));
//
// BAD
//
throw 'I have no call-stack no interesting properties.';
//
// BAD
//
callback('I have no call-stack no interesting properties.');
//
// BAD
//
throw { message: 'I have no call-stack no interesting properties.' };
//
// BAD
//
callback({
message: 'I have no call-stack no interesting properties.'
});
出口
- 欧盟驻科法治团: 如果您正在出口某物, 它 应 以与声明相同的线导出.
这使得人们更容易了解在同样的情况下立即出口什么.
//
// GOOD
//
var Foo = exports.Foo = function () {
//...
};
//
// BAD
//
var Foo = function () {
//...
};
//
// Lots of other code changing my mental context
// by the time I see Foo again I forgot what it was.
//
exports.Foo = Foo;
Async 编程
- 欧盟驻科法治团时间轴: 绝对不能 使用承诺.
- 欧盟驻科法治团时间轴: 必须 使用情况 自动同步。 。 。 .
只需使用Aync。 如果你爱承诺,那么对不起,这个决定 最终和 不得辩论 永远.
//
// GOOD
//
var async = require('async');
//
// BAD
//
var Q = require('q');
- 欧盟驻科法治团: 给定函数 绝对不能 拥有多于 3个 调用函数.
规则三。 你说什么? 它在童话中起作用.
这里的服务器模型
- 欧盟驻科法治团: 已命名函数 应 优先使用匿名内线函数.
归属(有修改和增补)
- https://github.com/cloudhead/styleguide/blob/master/JavaScript.md 互联网档案馆的存檔,存档日期2014-12-22
- https://github.com/airbnb/javascript
以下文件包括从
eslint-config-godaddy与麻省理工学院的归属
GoDaddy运营公司 2016index.js bin/eslint-autofix.js2017年查理·罗宾斯的修改