Javascript显式块

The*_*ory 3 javascript closures scope

我最近才知道 explicit block

{
   let foo = 'Hello';
   someFunction(foo);
}
Run Code Online (Sandbox Code Playgroud)

我仍然不太确定它的作用以及我们(开发人员)如何从中受益.

  • 你以前用过吗?
  • 你有用例吗?

感谢您分享您的体验!

T.J*_*der 7

因为let(和constclass和-在严格模式-函数声明)有块范围为ES2015的,你可以使用一个单独的块的私人信息,只是一般的更精细控制的变量,我们习惯用IIFEs范围.

也就是说,这里有一些ES5和早期代码有一个私有变量,x:

(function() {
    var x = Math.random();
    console.log(x);
})();
// `x` doesn't exist here
Run Code Online (Sandbox Code Playgroud)

x 很好地包含了那个IIFE.

现在,使用ES2015,我们可以在不创建和调用函数的情况下执行相同的操作:

{
    let x = Math.random();
    console.log(x);
}
// `x` doesn't exist here
Run Code Online (Sandbox Code Playgroud)

同样,由于独立块让我们控制变量范围,我们可以更明确地控制闭包的内容.例如,考虑一下:

function doSomething() {
    let retainedInformation;
    {
        let something = /*...get some setup information...*/;
        let anotherThing = /*...more setup information...*/;
        let aThirdThing = /*...even more setup information...*/;
        retainedInformation = /*...something figured out using the above...*/;
    }
    return function() {
        // ...use `retainedInformation`...
    };
}
Run Code Online (Sandbox Code Playgroud)

从那以后something,anotherThing, andaThirdThing are all out of scope for the function returned bydoSomething retainInformation` , they aren't retained by it, just就是.

但是现代JavaScript引擎无论如何都已经进行了闭包优化,并且所有这些设置可能最适合你在doSomething任何时候调用的函数,只是基于一般原则.


也就是说,我们仍然可能会看到很多IIFE,因为它们可以返回一个值.所以,例如,如果我想要一个使用私有变量的函数,我可能会这样做:

const foo = function() {
    let privateInfo = 42;
    const foo = () => {
        console.log(privateInfo++);
    };
    return foo;
}();
foo(); // 42
foo(); // 43
Run Code Online (Sandbox Code Playgroud)

而不是

let foo;
{
    let privateInfo = 42;
    foo = () => {
        console.log(privateInfo++);
    };
}
foo(); // 42
foo(); // 43
Run Code Online (Sandbox Code Playgroud)

......虽然两者都有效.