简体   繁体   English

下面的javascript代码段是做什么的

[英]What is the javascript snippet below doing

I see some code snippet as below while learning the Javascript, I am not sure about it, could you please advise what this structure exactly does, and when to use? 在学习Javascript时,我会看到一些如下的代码段,但我不确定,请您告知此结构的确切功能以及何时使用?

(function abc() 
{
     //action code here
})();

example

(function test() {
     alert(1);
})();

Thank you much. 非常感谢

The best you can do is to read this article: 最好的办法是阅读本文:

JavaScript Module Pattern: In-Depth JavaScript模块模式:深入

Smalle cite: Smalle引用:

Anonymous Closures 匿名关闭

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
}());

But really go through this article and observe what we do have, thanks to others, who described JS patterns for us... 但是要认真阅读本文,并感谢其他人为我们介绍了JS模式,请观察我们的工作...

Because the more imprtant piece is the MODULE pattern 因为最重要的是MODULE模式

Module Export 模块导出

Sometimes you don't just want to use globals, but you want to declare them. 有时,您不仅要使用全局变量,还想声明它们。 We can easily do this by exporting them, using the anonymous function's return value. 通过使用匿名函数的返回值导出它们,我们可以轻松地做到这一点。 Doing so will complete the basic module pattern, so here's a complete example: 这样做将完成基本的模块模式,因此这是一个完整的示例:

var MODULE = (function () {
    var my = {},
        privateVariable = 1;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
    };

    return my;
}());

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

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