简体   繁体   中英

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?

(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

Smalle cite:

Anonymous Closures

This is the fundamental construct that makes it all possible, and really is the single best feature of 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...

Because the more imprtant piece is the MODULE pattern

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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