string
number
boolean
null
undefined
var
foo = 1;
var
bar = foo;
bar = 9;
console.log(foo, bar);
// => 1, 9
|
object
array
function
var
foo = [1, 2];
var
bar = foo;
bar[0] = 9;
console.log(foo[0], bar[0]);
// => 9, 9
|
// bad
var
item =
new
Object();
// good
var
item = {};
|
// bad
var
superman = {
default
: { clark:
'kent'
},
private:
true
};
// good
var
superman = {
defaults: { clark:
'kent'
},
hidden:
true
};
|
// bad
var
superman = {
class:
'alien'
};
// bad
var
superman = {
klass:
'alien'
};
// good
var
superman = {
type:
'alien'
};
|
// bad
var
items =
new
Array();
// good
var
items = [];
|
var
someStack = [];
// bad
someStack[someStack.length] =
'abracadabra'
;
// good
someStack.push(
'abracadabra'
);
|
var
len = items.length;
var
itemsCopy = [];
var
i;
// bad
for
(i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
// good
itemsCopy = items.slice();
|
function
trigger() {
var
args = Array.prototype.slice.call(arguments);
...
}
|
''
包裹字符串。
// bad
var
name =
"Bob Parr"
;
// good
var
name =
'Bob Parr'
;
// bad
var
fullName =
"Bob "
+
this
.lastName;
// good
var
fullName =
'Bob '
+
this
.lastName;
|
// 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.'
;
|
var
items;
var
messages;
var
length;
var
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 =
'
;
for
(i = 0; i < length; i++) {
items +=
'
+ messages[i].message +
''
;
}
return
items +
''
;
}
// good
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('
') + '
';
}
|
// 匿名函数表达式
var
anonymous =
function
() {
return
true
;
};
// 命名函数表达式
var
named =
function
named() {
return
true
;
};
// 立即调用的函数表达式(IIFE)
(
function
() {
console.log(
'Welcome to the Internet. Please follow me.'
);
}());
|
块
定义为一组语句。函数声明不是语句。阅读对 ECMA-262 这个问题的说明。(http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf#page=97)
// 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...
}
|
.
来访问对象的属性。
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'
);
|
var
来声明变量。不这么做将导致产生全局变量。我们要避免污染全局命名空间。
// bad
superPower =
new
SuperPower();
// good
var
superPower =
new
SuperPower();
|
var
声明每一个变量。;
跟 ,
。
// bad
var
items = getItems(),
goSportsTeam =
true
,
dragonball =
'z'
;
// bad
// (跟上面的代码比较一下,看看哪里错了)
var
items = getItems(),
goSportsTeam =
true
;
dragonball =
'z'
;
// good
var
items = getItems();
var
goSportsTeam =
true
;
var
dragonball =
'z'
;
|
// bad
var
i, len, dragonball,
items = getItems(),
goSportsTeam =
true
;
// bad
var
i;
var
items = getItems();
var
dragonball;
var
goSportsTeam =
true
;
var
len;
// good
var
items = getItems();
var
goSportsTeam =
true
;
var
dragonball;
var
length;
var
i;
|
// bad
function
() {
test();
console.log(
'doing stuff..'
);
//..other stuff..
var
name = getName();
if
(name ===
'test'
) {
return
false
;
}
return
name;
}
// good
function
() {
var
name = getName();
test();
console.log(
'doing stuff..'
);
//..other stuff..
if
(name ===
'test'
) {
return
false
;
}
return
name;
}
// bad - 不必要的函数调用
function
() {
var
name = getName();
if
(!arguments.length) {
return
false
;
}
this
.setFirstName(name);
return
true
;
}
// good
function
() {
var
name;
if
(!arguments.length) {
return
false
;
}
name = getName();
this
.setFirstName(name);
return
true
;
}
|
// 我们知道这样不能正常工作(假设这里没有名为 notDefined 的全局变量)
function
example() {
console.log(notDefined);
// => throws a ReferenceError
}
// 但由于变量声明提升的原因,在一个变量引用后再创建它的变量声明将可以正常工作。
// 注:变量赋值为 `true` 不会提升。
function
example() {
console.log(declaredButNotAssigned);
// => undefined
var
declaredButNotAssigned =
true
;
}
// 解释器会把变量声明提升到作用域顶部,意味着我们的例子将被重写成:
function
example() {
var
declaredButNotAssigned;
console.log(declaredButNotAssigned);
// => undefined
declaredButNotAssigned =
true
;
}
|
function
example() {
console.log(anonymous);
// => undefined
anonymous();
// => TypeError anonymous is not a function
var
anonymous =
function
() {
console.log(
'anonymous function expression'
);
};
}
|
function
example() {
console.log(named);
// => undefined
named();
// => TypeError named is not a function
superPower();
// => ReferenceError superPower is not defined
var
named =
function
superPower() {
console.log(
'Flying'
);
};
}
// 当函数名跟变量名一样时,表现也是如此。
function
example() {
console.log(named);
// => undefined
named();
// => TypeError named is not a function
var
named =
function
named() {
console.log(
'named'
);
}
}
|
function
example() {
superPower();
// => Flying
function
superPower() {
console.log(
'Flying'
);
}
}
|
===
和 !==
而不是 ==
和 !=
. 条件表达式例如 if
语句通过抽象方法 ToBoolean
强制计算它们的表达式并且总是遵守下面的规则:
''
被计算为 false,否则为 true
if
([0]) {
// true
// 一个数组就是一个对象,对象被计算为 true
}
|
// bad
if
(name !==
''
) {
// ...stuff...
}
// good
if
(name) {
// ...stuff...
}
// bad
if
(collection.length > 0) {
// ...stuff...
}
// good
if
(collection.length) {
// ...stuff...
}
|
// bad
if
(test)
return
false
;
// good
if
(test)
return
false
;
// good
if
(test) {
return
false
;
}
// bad
function
() {
return
false
; }
// good
function
() {
return
false
;
}
|
if
和 else
使用多行代码块,把 else
放在 if
代码块关闭括号的同一行。
// bad
if
(test) {
thing1();
thing2();
}
else
{
thing3();
}
// good
if
(test) {
thing1();
thing2();
}
else
{
thing3();
}
|
/** ... */
作为多行注释。包含描述、指定所有参数和返回值的类型和值。
// bad
// make() returns a new element
// based on the passed in tag name
//
// @param {String} tag
// @return {Element} element
function
make(tag) {
// ...stuff...
return
element;
}
// good
/**
* make() returns a new element
* based on the passed in tag name
*
* @param {String} tag
* @return {Element} element
*/
function
make(tag) {
// ...stuff...
return
element;
}
|
//
作为单行注释。在评论对象上面另起一行使用单行注释。在注释前插入空行。
// bad
var
active =
true
;
// is current tab
// good
// is current tab
var
active =
true
;
// bad
function
getType() {
console.log(
'fetching type...'
);
// set the default type to 'no type'
var
type =
this
.type ||
'no type'
;
return
type;
}
// good
function
getType() {
console.log(
'fetching type...'
);
// set the default type to 'no type'
var
type =
this
.type ||
'no type'
;
return
type;
}
|
给注释增加 FIXME
或 TODO
的前缀可以帮助其他开发者快速了解这是一个需要复查的问题,或是给需要实现的功能提供一个解决方式。这将有别于常见的注释,因为它们是可操作的。使用 FIXME -- need to figure this out
或者 TODO -- need to implement
。
使用 // FIXME:
标注问题。
function
Calculator() {
// FIXME: shouldn't use a global here
total = 0;
return
this
;
}
|
// TODO:
标注问题的解决方式。
function
Calculator() {
// TODO: total should be configurable by an options param
this
.total = 0;
return
this
;
}
|
// bad
function
() {
∙∙∙∙
var
name;
}
// bad
function
() {
∙
var
name;
}
// good
function
() {
∙∙
var
name;
}
|
// bad
function
test(){
console.log(
'test'
);
}
// good
function
test() {
console.log(
'test'
);
}
// bad
dog.set(
'attr'
,{
age:
'1 year'
,
breed:
'Bernese Mountain Dog'
});
// good
dog.set(
'attr'
, {
age:
'1 year'
,
breed:
'Bernese Mountain Dog'
});
|
if
、while
等)的小括号前放一个空格。在函数调用及声明中,不在函数的参数列表前加空格。
// bad
if
(isJedi) {
fight ();
}
// good
if
(isJedi) {
fight();
}
// bad
function
fight () {
console.log (
'Swooosh!'
);
}
// good
function
fight() {
console.log(
'Swooosh!'
);
}
|
// bad
var
x=y+5;
// good
var
x = y + 5;
|
// bad
(
function
(global) {
// ...stuff...
})(
this
);
// bad
(
function
(global) {
// ...stuff...
})(
this
);↵
↵
// good
(
function
(global) {
// ...stuff...
})(
this
);↵
|
.
强调这是方法调用而不是新语句。
// bad
$(
'#items'
).find(
'.selected'
).highlight().end().find(
'.open'
).updateCount();
// bad
$(
'#items'
).
find(
'.selected'
).
highlight().
end().
find(
'.open'
).
updateCount();
// good
$(
'#items'
)
.find(
'.selected'
)
.highlight()
.end()
.find(
'.open'
)
.updateCount();
// bad
var
leds = stage.selectAll(
'.led'
).data(data).enter().append(
'svg:svg'
).classed(
'led'
,
true
)
.attr(
'width'
, (radius + margin) * 2).append(
'svg:g'
)
.attr(
'transform'
,
'translate('
+ (radius + margin) +
','
+ (radius + margin) +
')'
)
.call(tron.led);
// good
var
leds = stage.selectAll(
'.led'
)
.data(data)
.enter().append(
'svg:svg'
)
.classed(
'led'
,
true
)
.attr(
'width'
, (radius + margin) * 2)
.append(
'svg:g'
)
.attr(
'transform'
,
'translate('
+ (radius + margin) +
','
+ (radius + margin) +
')'
)
.call(tron.led);
|
// bad
if
(foo) {
return
bar;
}
return
baz;
// good
if
(foo) {
return
bar;
}
return
baz;
// bad
var
obj = {
foo:
function
() {
},
bar:
function
() {
}
};
return
obj;
// good
var
obj = {
foo:
function
() {
},
bar:
function
() {
}
};
return
obj;
|
// bad
var
story = [
once
, upon
, aTime
];
// good
var
story = [
once,
upon,
aTime
];
// bad
var
hero = {
firstName:
'Bob'
, lastName:
'Parr'
, heroName:
'Mr. Incredible'
, superPower:
'strength'
};
// good
var
hero = {
firstName:
'Bob'
,
lastName:
'Parr'
,
heroName:
'Mr. Incredible'
,
superPower:
'strength'
};
|
> Edition 5 clarifies the fact that a trailing comma at the end of an ArrayInitialiser does not add to the length of the array. This is not a semantic change from Edition 3 but some implementations may have previously misinterpreted this.
// bad
var
hero = {
firstName:
'Kevin'
,
lastName:
'Flynn'
,
};
var
heroes = [
'Batman'
,
'Superman'
,
];
// good
var
hero = {
firstName:
'Kevin'
,
lastName:
'Flynn'
};
var
heroes = [
'Batman'
,
'Superman'
];
|
// bad
(
function
() {
var
name =
'Skywalker'
return
name
})()
// good
(
function
() {
var
name =
'Skywalker'
;
return
name;
})();
// good (防止函数在两个 IIFE 合并时被当成一个参数
;(
function
() {
var
name =
'Skywalker'
;
return
name;
})();
|
[了解更多](http://stackoverflow.com/a/7365214/1712802).
// => 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
转换数字时总是带上类型转换的基数。
var
inputValue =
'4'
;
// bad
var
val =
new
Number(inputValue);
// bad
var
val = +inputValue;
// bad
var
val = inputValue >> 0;
// bad
var
val = parseInt(inputValue);
// good
var
val = Number(inputValue);
// good
var
val = parseInt(inputValue, 10);
|
parseInt
成为你所做的事的瓶颈而需要使用位操作解决性能问题(http://jsperf.com/coercion-vs-casting/3)时,留个注释说清楚原因和你的目的。
// 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;
|
2147483647 >> 0
//=> 2147483647
2147483648 >> 0
//=> -2147483648
2147483649 >> 0
//=> -2147483647
|
var
age = 0;
// bad
var
hasAge =
new
Boolean(age);
// good
var
hasAge = Boolean(age);
// good
var
hasAge = !!age;
|
getVal()
和 setVal('hello')
。
// bad
dragon.age();
// good
dragon.getAge();
// bad
dragon.age(25);
// good
dragon.setAge(25);
|
isVal()
或 hasVal()
。
// bad
if
(!dragon.age()) {
return
false
;
}
// good
if
(!dragon.hasAge()) {
return
false
;
}
|
function
Jedi(options) {
options || (options = {});
var
lightsaber = options.lightsaber ||
'blue'
;
this
.set(
'lightsaber'
|