为什么{position会影响这个Javascript代码? [英] Why does the { position affects this Javascript code?

查看:93
本文介绍了为什么{position会影响这个Javascript代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个Javascript问题上花了相当多的时间(你可以告诉我我是一个JS菜鸟):

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

写一些写得好的Javascript代码这个例子

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

运行它的工作原理精细。然后将{移动到下一行(作为C#开发人员,我设置了所有环境,将花括号放在新行上)并再次运行。

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
  };

现在围绕13换行错误'返回'会出现相当多的JS错误。和Chrome调试器中的Uncaught SyntaxError:Unexpected token:。

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

我的问题是,如何在语法上影响这样的Javascript?

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

我已经在JSFiddle中设置它(为了让它工作,移动{在返回之后返回同一行)

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

推荐答案

JavaScript最糟糕的功能之一是自动分号插入。

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

return; // a semicolon is implicitly inserted here

这部分几乎是有效的JavaScript,但不完全,所以你得到一个语法错误:

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

{
    someMethod : myMethod,
    someOtherMethod : myOtherMethod
};

如果您曾尝试这样做:

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

它刚刚返回 undefined 所有时间,那本来就不好。 ASI很糟糕,但我们现在坚持使用它,特别是因为无分色代码已成为一种时尚。

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.

这是做什么的?

return a
     + b
     + c;

这个?

return e
     / f /g;

好吧,好吧,也许这个人有点做作,也许这不完全是热门话题。但ASI很糟糕。我希望每个人都能得到这个。

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.

这篇关于为什么{position会影响这个Javascript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆