JavaScript空白语法错误 [英] JavaScript Whitespace Syntax Error
问题描述
var FOO =(function($)
{
return
{
init:function()
{
$ b}
}
})(jQuery);
不过:
<$ p
$ {
$ {$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ }
}
})(jQuery);
为什么会有差异?
这不是关于空格,而是JavaScript的自动分号插入。
ECMAScript规范说明
某些ECMAScript语句(空的
语句,变量语句,
表达式语句,do-while
语句,continue语句,break
语句,返回语句和抛出
语句)必须以
分号结尾。这样的分号可以总是
显示在源文本中。
但是,为了方便起见,在某些情况下,可能会从
源文本中省略这样的
分号。
这些情况被描述为
,表示在这种情况下,分号是
自动插入源
代码标记流中。
这意味着你的代码
var FOO =(function($)
{
return
{
init:function()
{
$ b}
}
})(jQuery);
被翻译为
var FOO =(function($)
{
return; //< - JavaScript会在这里插入一个分号
{
init:function()
{
}
}
})(jQuery);
所以FOO在函数执行后将会被定义。
对于其他代码, JS不会插入任何分号,它将正常工作 JS会在您的字面值对象之后插入分号,它应该工作正常。
这意味着你应该总是用分号终止你的语句。让JS引擎插入分号可以引入非常微妙的错误,这将花费几个小时来调试。您可以使用像 JSLint 这样的工具,它会警告您缺少分号。
Why does this cause a syntax error for the return statement:
var FOO = (function($)
{
return
{
init: function()
{
}
}
})(jQuery);
Whereas this doesn't:
var FOO = (function($)
{
return {
init: function()
{
}
}
})(jQuery);
Why is there a difference?
It's not about the whitespace, it's about automatic semicolon insertion by JavaScript.
ECMAScript specification says
Certain ECMAScript statements (empty statement, variable statement, expression statement, do-while statement, continue statement, break statement, return statement, and throw statement) must be terminated with semicolons. Such semicolons may always appear explicitly in the source text. For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.
This means that your code
var FOO = (function($)
{
return
{
init: function()
{
}
}
})(jQuery);
gets translated as
var FOO = (function($)
{
return; // <- JavaScript will insert a semicolon here.
{
init: function()
{
}
}
})(jQuery);
So FOO will be undefined after the function is executed.
For your other code, JS won't insert any semicolon and it will work correctly JS will insert semicolon after your literal object and it should work fine. [EDIT: Correction as pointed out by kagnax]
This means that you should always terminate your statements with semicolon. Letting JS engine insert semicolon can introduce very subtle bugs, which would take hours to debug. You can use a tool like JSLint which will warn you of missing semicolons.
这篇关于JavaScript空白语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!