javascript编码规范
Types
原始类型
- string
- number
- boolen
- null
- undefined
复杂类型
- string
- number
- boolen
Objects
使用大括号创建对象;不使用关键字、保留字作为键(在IE8或更早浏览器下会出错);使用易读的同义词代替保留字。
//good
var obj = {};
var obj = {
defaults : { len: 1 }
};
Arrays
使用中括号创建数组;使用push方法而不是直接赋值将项目添加到数组;使用slice方法复制数组;类似数组的对象转换成一个数组,使用slice
//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而不是字符串拼接建立一个新字符串
//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
// 匿名函数表达式
var anonymous = function () {
return true;
};
// 命名函数表达式
var named = function named() {
return true;
};
// 立即调用的函数表达式 (IIFE)
(function () {
console.log(‘Welcome to the Internet. Please follow me.’);
}());
不要再 if、 while 等代码块中定义函数
// bad
if (currentUser) {
function test() {
console.log(‘Nope.’);
}
}
// good
var test;
if (currentUser) {
test = function test() {
console.log(‘Yup.’);
};
}
不要使用arguments作为参数,它将覆盖原生的arguments
// bad
function nope(name, options, arguments) {
// …stuff…
}
// good
function yup(name, options, args) {
// …stuff…
}
Properties
访问属性时使用.符号
var luke = { jedi: true, age: 28 }; // bad var isJedi = luke[‘jedi’]; // good var isJedi = luke.jedi;
当访问变量的属性使用下标符号[]。
var luke = {
jedi: true,
age: 28
};
function getProp(prop) {
return luke[prop];
}
var isJedi = getProp(‘jedi’);
未完待续