JavaScript 解释器做了一种叫做“分号插入”的事情,所以如果没有分号的行是有效的,分号会悄悄地添加到语句的末尾,不会发生错误。
var foo = 'bar'
// Valid, foo now contains 'bar'
var bas =
{ prop: 'yay!' }
// Valid, bas now contains object with property 'prop' containing 'yay!'
var zeb =
switch (zeb) {
...
// Invalid, because the lines following 'var zeb =' aren't an assignable value
不太复杂,至少当某些事情明显不正确时会引发错误。但是有些情况下没有抛出错误,但是由于分号插入,语句没有按预期执行。考虑一个应该返回对象的函数:
return {
prop: 'yay!'
}
// The object literal gets returned as expected and all is well
return
{
prop: 'nay!'
}
// Oops! return by itself is a perfectly valid statement, so a semicolon
// is inserted and undefined is unexpectedly returned, rather than the object
// literal. Note that no error occurred.
像这样的错误很难找到,虽然你不能确保这种情况永远不会发生(因为我不知道关闭分号插入),但当你通过以下方式明确意图时,这些错误更容易识别始终使用分号。这和明确添加分号通常被认为是好的风格。
在阅读Douglas Crockford 的精妙而简洁的著作《JavaScript: The Good Parts 》时,我第一次意识到了这种隐蔽的小可能性。我强烈推荐它。