Why does the { position affects this Javascript code?

前端 未结 5 1379
夕颜
夕颜 2020-12-20 22:03

I spent a fair bit of time on this Javascript issue (you can tell I am a JS noob):

Take some well written Javascript code like this example of the Revealing Module P

5条回答
  •  误落风尘
    2020-12-20 22:23

    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.

提交回复
热议问题