在JavaScript中进行对象文字赋值后是否需要分号? [英] Are semicolons needed after an object literal assignment in JavaScript?

查看:86
本文介绍了在JavaScript中进行对象文字赋值后是否需要分号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码说明了分配的对象文字,但之后没有分号:

The following code illustrates an object literal being assigned, but with no semicolon afterwards:

var literal = {
    say: function(msg) { alert(msg); }
}
literal.say("hello world!");

这似乎是合法的,并且不会发出警告(至少在Firefox  3中) 。这是完全合法的,还是有严格版本的JavaScript不允许这样做?

This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed?

我特别想知道未来的兼容性问题......我想要写正确的JavaScript,所以如果技术上我需要使用分号,我想使用它。

I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.

推荐答案

从技术上讲,JavaScript在许多情况下都有分号作为可选项。

Not technically, JavaScript has semicolons as optional in many situations.

但是,作为一般规则,在任何声明的最后使用它们。为什么?因为如果您想要压缩脚本,它将为您节省无数个小时的挫折感。

But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration.

自动分号插入由解释器执行,因此您可以如果您愿意,请将它们排除在外。在评论中,有人声称

Automatic semicolon insertion is performed by the interpreter, so you can leave them out if you so choose. In the comments, someone claimed that


分号不是可选的,如break / continue / throw

Semicolons are not optional with statements like break/continue/throw

但这是不正确的。它们是可选的;真正发生的是线路终结器影响自动分号插入;这是一个微妙的差异。

but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference.

以下是分号插入标准的其余部分:

Here is the rest of the standard on semicolon insertion:


为方便起见但是,在某些情况下,源文本中可能会省略这样的分号。这些情况通过说在这些情况下分号自动插入源代码令牌流来描述。

For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.

这篇关于在JavaScript中进行对象文字赋值后是否需要分号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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