Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

revealing module pattern - Why does the { position affects this Javascript code?

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 Pattern:

Running it works fine. Then move the "{" to the next line (as a C# developer I set up all my environments to put curly braces on new lines) and run it again.

  return   
  {
    someMethod : myMethod,
    someOtherMethod : myOtherMethod
  };

It now gets quite a few JS errors around "13 Line breaking error 'return'." and "Uncaught SyntaxError: Unexpected token : " in Chrome Debugger.

My question is, how can something syntactically affect the Javascript like this?

I have set it up here in JSFiddle (to get it to work, move the { after "return" back on to the same line)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...