What is this code in Javascript?

In some JS codes on some sites, I see Javascript code, for example:

SomeName.init = (function () {
    // some stuff
})();

I mean, this is not jQuery plugin code such as:

(function( $ ){
    $.fn.myPlugin = function() {

    // Do your awesome plugin stuff here

    };
})( jQuery );

Then what is it? and what is the resulting js object?

+5
source share
4 answers

Module template . And these two fragments have more in common than you think.

+2
source

This is an anonymous function that does not transfer variables to the global scope when declaring variables with var.

SomeName.init = (function () {
    return 3.1415;
})();

SomeName.init - (3.1415), () . , :

(function foo(){
    //foo refers to this function
    too = foo;
})();;
//foo is undefined
//too refers to the function, because `too` has been defined without var
+8
(function () {
    // some stuff
})()

- An anonymous function that calls itself instantly. This is just a closure inside the code to stop the scope of the variable, becoming global.

+1
source

Regardless of the return function.

(function() {
    //...
})();

Used as a way to namespace code or declares self-executing constructors. The resulting object is what the self-executing function returns.

The second fragment returns nothing and does not exist resulting JS object.

0
source

All Articles