Why does the { position affects this Javascript code?

给你一囗甜甜゛ 提交于 2019-11-29 14:36:59

One of JavaScript’s worst features is Automatic Semicolon Insertion.

return; // a semicolon is implicitly inserted here

And this part is almost valid JavaScript, but not quite, so you get a syntax error:

{
    someMethod : myMethod,
    someOtherMethod : myOtherMethod
};

If you had tried to do this:

return
    [ 1, 2, 3,
      4, 5, 6,
      7, 8, 9 ];

it would have just returned undefined all the time, and that would have been bad. ASI sucks, but we’re stuck with it now, especially since semicolonless code has become a fad.

What does this do?

return a
     + b
     + c;

This?

return e
     / f /g;

Okay, okay, maybe that one’s a bit contrived, and maybe this isn’t entirely topical. But ASI is bad. I hope everyone gets that.

Because the ECMA standard section 12.9 states you can't have a new line between the return keyword and its expression.

    ReturnStatement :
       return ;
       return [no LineTerminator here] Expression ;

Javascript does something called Automatic semi-colon insertion which I believe is what is affecting your results here. Basically, it sees the return statement with nothing after on the line, and thinks that's the end of the line and returns, ending the function.

Because return expects a value (or variable), when you put the curly brace in the same line you are telling return a hash but if you move the curly brace to the next line then you are telling return nothing so the next line is not expected.

EDIT The next line is not expected in the context of return.

Javascript has some strange bits to it and one is that the position of the brackets matters - keep the opening one on the same line as the code

http://encosia.com/in-javascript-curly-brace-placement-matters-an-example/

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