javascript编码规范

Types

原始类型

  • string
  • number
  • boolen
  • null
  • undefined

复杂类型

  • string
  • number
  • boolen

Objects

使用大括号创建对象;不使用关键字、保留字作为键(在IE8或更早浏览器下会出错);使用易读的同义词代替保留字。

1
2
3
4
5
 //good
var obj = {};
var obj = {
defaults : { len: 1 }
};

Arrays

使用中括号创建数组;使用push方法而不是直接赋值将项目添加到数组;使用slice方法复制数组;类似数组的对象转换成一个数组,使用slice方法

1
2
3
4
5
6
7
8
9
 //good
var arr = \[\];
var arr = \[a,b,c\];
arr.push(str);
arrCopy = arr.slice();
function trigger() {
var args = Array.prototype.slice.call(arguments);
...
}

Strings

字符串使用单引号;超过100字符的字符串应该写跨多个使用字符串连接,如果过度使用,长字符串连接可能会影响性能;使用数组join而不是字符串拼接建立一个新字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//good
var str = '字符串';
//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 items
,messages
,var 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;
function inbox(messages) {
items = \[\];
for (i = 0; i < length; i++) {
// use direct assignment in this case because we're micro-optimizing.
items\[i\] = '* ' + messages\[i\].message + '
';
}
return '

' + items.join('') + '

';
}

Functions

1
2
3
4
5
6
7
8
9
10
11
12
// 匿名函数表达式
var anonymous = function () {
return true;
};
// 命名函数表达式
var named = function named() {
return true;
};
// 立即调用的函数表达式 (IIFE)
(function () {
console.log('Welcome to the Internet. Please follow me.');
}());

不要再 if、 while 等代码块中定义函数

1
2
3
4
5
6
7
8
9
10
11
12
13
// bad
if (currentUser) {
function test() {
console.log('Nope.');
}
}
// good
var test;
if (currentUser) {
test = function test() {
console.log('Yup.');
};
}

不要使用arguments作为参数,它将覆盖原生的arguments

1
2
3
4
5
6
7
8
// bad
function nope(name, options, arguments) {
// ...stuff...
}
// good
function yup(name, options, args) {
// ...stuff...
}

Properties

访问属性时使用.符号

1
var luke = { jedi: true, age: 28 }; // bad var isJedi = luke\['jedi'\]; // good var isJedi = luke.jedi;

当访问变量的属性使用下标符号[]。

1
2
3
4
5
6
7
8
var luke = {
jedi: true,
age: 28
};
function getProp(prop) {
return luke\[prop\];
}
var isJedi = getProp('jedi');

airbnb

未完待续


javascript编码规范
https://cszy.top/2016-05-05 javascript编码规范/
作者
csorz
发布于
2016年5月5日
许可协议