为什么会导致return语句出现语法错误:
var FOO = (function($)
{
return
{
init: function()
{
}
}
})(jQuery);
而这不是:
var FOO = (function($)
{
return {
init: function()
{
}
}
})(jQuery);
为什么会有差异?
最佳答案
这不是关于空格,而是关于 JavaScript 自动插入分号。
ECMAScript 规范说
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.
这意味着你的代码
var FOO = (function($)
{
return
{
init: function()
{
}
}
})(jQuery);
翻译成
var FOO = (function($)
{
return; // <- JavaScript will insert a semicolon here.
{
init: function()
{
}
}
})(jQuery);
所以函数执行后 FOO 将是未定义的。
对于您的其他代码,JS 不会插入任何分号,它会正常工作 JS 会在您的文字对象之后插入分号,它应该可以正常工作。 [编辑:kagnax 指出的更正]
这意味着您应该始终以分号结束您的语句。让 JS 引擎插入分号会引入非常微妙的错误,这需要数小时才能调试。您可以使用 JSLint 之类的工具这将警告您缺少分号。
关于JavaScript 空格语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1549936/