自动分号插入&退货声明 [英] Automatic semicolon insertion & return statements

查看:180
本文介绍了自动分号插入&退货声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如您可能知道的那样,ECMAscript会尝试变聪明,并且如果您没有明确地编写分号,则会自动插入分号。简单示例

As you might know, ECMAscript tries to be smart and will automatically insert semicolons if you didn't write those explicitly. Simple example

function foo() {
    var bar = 5

    return bar
}

仍将按预期工作。但如果你依赖它,有一些警告。如果我们像这样重写那个函数

will still work as expected. But there are some caveats if you rely on that. If we re-write that function like so

function foo() {
    var bar = 5

    return
    {
        bar: bar
    }
}

..该函数现在将返回 undefined 因为解释器会在返回后立即插入分号声明(这就是为什么你总是应该把大括号放在同一行作为声明的原因)。

..that function would now return undefined because the interpreter would insert that semicolon right after the return statement (that's a reason why you always should bring curly brackets on the same line as a statement).

然而,知道所有这些我现在想知道如何安全 返回语句,如下所示,跨浏览器和版本

However, knowing all this I'm wondering now how safe a return statement like the following is, across browsers and versions

function foo() {
    var a = true,
        b = true,
        c = false;

    return a 
            && b
            && c;
}

我刚写了类似的返回语句在生产环境中。仅仅因为我知道ECMAscript的问题对分号插入不太明智我现在想知道,如果该代码100%工作。在我对FF / Chrome / IE(最新版本)的第一次测试中,这似乎完全没问题,但是真的吗?

I just wrote a similar return statement in a production environment. Just because I knew about the "problems" with ECMAscript beeing not-so-smart about semicolon insertion I'm wondering now, if that code works 100%. In my first tests on FF/Chrome/IE (latest versions) this seems to be totally fine, but is it really?

自动分号插入唤醒,除了该行中的 return 语句之外还有什么?任何人都可以提供有关此实现级别的详细信息吗?

Does the automatic semicolon insertion "wake-up" if there is anything else but the return statement in that line? Can anyone provide implementation-level detail about this?

推荐答案

javascript解释器/编译器非常智能,只有在事后才插入自动分号有效的Javascript。

The javascript interpreter/compiler is so smart to only insert automatic semicolons if afterwards there is valid Javascript.

您的代码有效,因为&& b 因为它不是有效的表达式 - 这就是为什么在返回之后没有插入分号的结果:

Your code works, because && b as it stands is no valid expression - that's why no semicolon gets inserted after the return a resulting in:

return a && b && c;

但是:

return (undefined);//implicitely inserted
{
    ....
}

完全有效,这就是分号插入的原因。

is perfectly valid and thats why a semicolon gets inserted.

为了完整起见,参考规范:自动分号插入。这些例子值得一读。

For completeness' sake the ref to the spec: automatic semicolon insertion. THe examples are worth reading through.

这篇关于自动分号插入&退货声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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