JavaScript代码书写风格(其他篇)
Opened this issue · 0 comments
LeeJim commented
注释风格
(line-comment-position) 注释使用//
,写在代码的上面,不要写在旁边:
// Bad
1 + 1; // valid comment
// Good
// valid comment
1 + 1;
变量相关
声明
(one-var-declaration-per-line) 声明时每个变量独占一行:
// Bad
var foo, bar, baz;
// Good
var foo,
bar,
baz;
(newline-after-var) 变量声明后需加一个空行:
// Bad
var greet = "hello,",
name = "world";
console.log(greet, name);
// Good
var greet = "hello,",
name = "world";
console.log(greet, name);
赋值
(operator-assignment) 使用赋值运算符
// Bad
x = x + y;
x = y * x;
// Good
x += y;
x *= y;
字符串
(quotes) 定义字符串变量,使用字面量以及单引号:
// Bad
var str = new String('123');
// Good
var str = '123';
数组
(no-array-constructor) 使用字面量定义:
// Bad
var arr = new Array();
// Good
var arr = [];
对象
- (no-new-object) 使用字面量定义:
// Bad
var obj = new Object();
// Good
var obj = {}
- (object-property-newline) 每个key和value独占一行:
// Bad
let a = {foo: 1, bar: 2};
// Good
let a = {
foo: 1,
bar: 2
};
其他风格
- (brace-style) 大括号风格
// Bad
if (true)
{
}
// Good
if (true) {
}
- (camelcase) 使用驼峰方式命名变量:
// Bad
var my_favorite_color = "#112C85";
// Good
var myFavoriteColor = "#112C85";
- (comma-style) 尾部逗号风格:
// Bad
var foo = 1
, bar = 2;
var foo = [
"apples"
, "oranges"
];
// Good
var foo = 1,
bar = 2;
var foo = [
"apples",
"oranges"
];
- (func-style) 使用函数表达式来定义函数:
// Bad
function foo() {
// ...
}
// Good
var foo = function() {
// ...
};