//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; functioninbox(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 () { returntrue; }; // 命名函数表达式 var named = functionnamed() { returntrue; }; // 立即调用的函数表达式 (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) { functiontest() { console.log('Nope.'); } } // good var test; if (currentUser) { test = functiontest() { console.log('Yup.'); }; }
不要使用arguments作为参数,它将覆盖原生的arguments
1 2 3 4 5 6 7 8
// bad functionnope(name, options, arguments) { // ...stuff... } // good functionyup(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 }; functiongetProp(prop) { return luke\[prop\]; } var isJedi = getProp('jedi');