简体   繁体   English

什么是匿名关闭,为什么与正常关闭不同?

[英]What is anonymous closure and why is it different from normal closure?

I started reading this: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth 我开始阅读以下内容: http : //www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

And they refer to anonymous closure: 他们指的是匿名关闭:

This is the fundamental construct that makes it all possible, and really is the single best feature of JavaScript. 这是使这一切成为可能的基本构造,实际上是JavaScript的唯一最佳功能。 We'll simply create an anonymous function, and execute it immediately. 我们将简单地创建一个匿名函数,并立即执行它。 All of the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application. 在函数中运行的所有代码都位于一个闭包中,该闭包在应用程序的整个生命周期内都提供了隐私状态

(function () {
    // ... all vars and functions are in this scope only
    // still maintains access to all globals
}());
  • I don't understand what happens in a self-executing anonymous function closure-wise, that is different from a normal closure and why is it so special? 我不明白在自执行匿名函数闭包方面会发生什么,这与普通闭包不同,为什么它如此特殊?
  • What is the benefit in it? 这样做有什么好处?

Variables that are not defined within a closure get into the window variable and are global. 在闭包中未定义的变量将进入window变量,并且是全局变量。

Example: 例:

var SOME_CONSTANT = 4;

function foo() { 
    var c = SOME_CONSTANT;
    console.log( c );
}

foo();

If you have this code, SOME_CONSTANT will be global to all files and code run within inline scripts etc, which may not be desired. 如果您有此代码,则SOME_CONSTANT对于所有文件都是全局的,并且代码在内联脚本等中运行,这可能是不希望的。

You can use the self-calling closure to keep the variable only inside this closure: 您可以使用自调用闭包将变量仅保留在此闭包内:

( function() {
    var SOME_CONSTANT = 4;

    function foo() {
        var c = SOME_CONSTANT;
        console.log( c );
    }

    foo();

} () );

This way you can have modules that have variables global only to that module. 这样,您可以使模块具有仅对该模块全局的变量。 For example, by having the code of each file enclosed in such an anonymous function. 例如,通过将每个文件的代码包含在这种匿名函数中。

除了立即执行此功能外,“正常关闭”没有任何区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM