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?
Module template . And these two fragments have more in common than you think.
This is an anonymous function that does not transfer variables to the global scope when declaring variables with var.
var
SomeName.init = (function () { return 3.1415; })();
SomeName.init - (3.1415), () . , :
SomeName.init
()
(function foo(){ //foo refers to this function too = foo; })();; //foo is undefined //too refers to the function, because `too` has been defined without var
(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.
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.
resulting JS object