问题描述
为什么这会导致return语句的语法错误: var FOO =(function($)
{
return
{
init:function()
{
$ b}
}
})(jQuery);
不过:
<$ p
$ {
$ {$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ }
}
})(jQuery);
为什么会有差异?
这不是关于空格,而是JavaScript的自动分号插入。
ECMAScript规范说明
这意味着你的代码
var FOO =(function($)
{
return
{
init:function()
{
$ b}
}
})(jQuery);
被翻译为
var FOO =(function($)
{
return; //< - JavaScript会在这里插入一个分号
{
init:function()
{
}
}
})(jQuery);
所以FOO在函数执行后将会被定义。
对于其他代码, JS会在您的字面值对象之后插入分号,它应该工作正常。
这意味着你应该总是用分号终止你的语句。让JS引擎插入分号可以引入非常微妙的错误,这将花费几个小时来调试。您可以使用像这样的工具,它会警告您缺少分号。
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
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 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空白语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!