3

I always assumed that all whitespace (spaces, tabs, newlines) in JavaScript source code was 'equal', i.e. they're all valid to separate language elements such as identifiers, keywords, operators, etc.

However, I noticed a strange difference between newlines versus spaces or tabs. Even inside comments!

This works OK: (line break between function definition and function call, but no semicolon)

var bla = function() { alert('hello') }
bla();

This also works: (semicolon between the closing } character and the bla() function call)

var bla = function() { alert('hello') };bla();

However, this does NOT work: (no difference whether there's just one space or tab, or multiple, or none)

var bla = function() { alert('hello') } bla();

And it gets even stranger.

This doesn't work either: (separated by comment containing space, tab and semicolon)

var bla = function() { alert('hello') } /*  ; */ bla();

But this does: (comment containing line break)

var bla = function() { alert('hello') }/*
*/bla();

Live jsfiddle demos:

Is this a bug in JavaScript, or am I missing something?

4

1 回答 1

5

这不归咎于空白行为不当,而是归结为 Javascript 的“ASI”功能:“自动分号插入”。

这是 Javascript 语言首次引入时包含的一项功能。基本上,交易是这样的:

核心 JS 语言要求每条语句都以分号结尾。

然而,因为该语言是针对网页设计者(当时他们不被认为是程序员),所以如果开发者忘记包含分号,解析器被修改为宽松。如果解析器认为缺少分号,但存在换行符,它将假设分号是有意的。

坦率地说,这在语言设计中是一个非常糟糕的决定:它导致了许多已知的怪癖,这些怪癖可能导致难以调试的问题。return特别是,对于返回多行对象结构的语句,您需要非常小心,但是正如您的问题所表明的那样,它可以通过许多其他方式来吸引您。

这里要学习的教训很简单:始终在 JS 语句之间包含分号,即使它们看起来是可选的。

如果您真的对该主题感兴趣,可以在此处阅读有关 ASI的更多信息,作为 Javascript 程序员,了解这一点很重要。但一般来说,如果你只包含分号,你几乎可以忘记它。

于 2013-10-24T09:38:38.037 回答