javascript: Why does this return statement cause a syntax error?

空扰寡人 提交于 2019-12-01 23:44:57

问题


I'm using Apatana 3, i modified the JS code formatter a little bit to let it seem more clear, below is the code after format, it give me an error:

    copyOffset : function( index )
    {
        return
        {
            x : index, y : index
        };
    }

firebug give me:

SyntaxError: invalid label

if i change it to:

    copyOffset : function( index )
    {
        return{
            x : index, y : index
        };
    }

will be OK, Anybody who can tell me what's the diff between these two return statement?


回答1:


The difference is that the first snippet is actually interpreted as...

copyOffset : function( index )
{
    return;
    {
        x : index, y : index
    };
}

It's called Automatic Semicolon Insertion: when JavaScript parser sees a statement that seems to be complete, but misses semicolon, it attempts to 'fix' it.

And yes, even though helpful at times, it can be quite annoying. This article explains this JavaScript feature in details.




回答2:


Haha, this is a classical one;)

Javasript breaks on

return
{

because it treats { as a new block and implicitely inserts a semicolon:

return;
{

thus returning undefined:-D

The Problem is Javasript inserting a Semicolon at the end of a line when the statement makes sense. Since return can stand on it's own, Javascript interprets it as a complete statement and inserts the semicolon, thus breaking your code.

Actually, this is the reason, why in Javascript you alway should avoid those newlines and write:

copyOffset : function( index ){
    return{
        x : index, y : index
    };
}


来源:https://stackoverflow.com/questions/12687464/javascript-why-does-this-return-statement-cause-a-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!