如何在这些javascript代码中理解花括号?

时间:2015-12-25 07:33:29

标签: javascript babeljs

我从ES6语法中获得了 babel-preset-es2015 生成的这样一段javascript代码,它可以正常运行,但我无法理解' {}& #39;请告诉我,thx。

{
    function foo () { alert(3);return 1 }
    foo() === 1
    {
        function foo () { alert(2) return 2 }
        foo() === 2
    }
    foo() === 1
}

根据ES6 API,这里的花括号表示自执行功能:

//  only in ES5 with the help of block-scope emulating
//  function scopes and function expressions
(function () {
    var foo = function () { alert(3);return 1; }
    foo() === 1;
    (function () {
        var foo = function () { alert(2);return 2; }
        foo() === 2;
    })();
    foo() === 1;
})();

如果使用ES5,它应该是:

Foo tinyint(1) unsigned NOT NULL DEFAULT 0,

但是,经过 babel-preset-es2015 编译后,它仍然使用' {}'而不是匿名的自执行功能。

所以,我很困惑,我从来没有听说过花括号的这种用法。

1 个答案:

答案 0 :(得分:0)

在这种情况下,花括号包含。在这种情况下,他们确定两个foo函数的方式不同。

{
    function foo () { alert(3);return 1 }
    foo() === 1 // we get an alert(3) and it returns 1
    {
        function foo () { alert(2) return 2 }
        foo() === 2 // we get an alert(2) and it returns 2
    }
    foo() === 1 // we get an alert(3) and it returns 1
}

如果代码是:

{
    function foo () { alert(3);return 1 }
    foo() === 1 // we get an alert(3) and it returns 1
    {
        // no definition of another foo function
        foo() === 2 // this evaluates to false; we still get an alert(3) and return 1
    }
    foo() === 1 // we get an alert(3) and it returns 1
}

有关详细信息,您可能需要研究范围闭包

圣诞快乐!