What does this type of function mean in javascript?

Below I am confused by the syntax

(function (h,j) { })

What does it mean that in javascript there is a function that is inside ()?

function myfunc(c, b) {
    try {
            (function (h, j) {
                //do a bunch of stuff
            })
    } catch (e) {
        myerror(e)
    }
};
+3
source share
4 answers

In itself, such a function declaration is useless. This kind of declaration is useful if you really call a function that executes as follows:

(function (h, j) { ... } (x, y));

This is usually done in order to hide the variables, since JavaScript has only scope (without block area).

Edit:

Some examples - hope this doesn't confuse things ...

As mentioned in the commentary, this method is useful for saving variables from the global scope. For example, some script initialization might do the following:

(function () {
    var x = 42;
    var y = 'foo';

    function doInitialisation(a, b) {
        // ...
    }

    doInitialisation(x, y);
}());

x, y doInitialisation .

. . :

var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    links[i].onclick = function () {
        alert(i);
    };
}

onclick i. :

var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    links[i].onclick = (function (x) {
        return function() {
            alert(x);
        }
    }(i));
}
+15

() - , .

,

> function(x,y) {}
SyntaxError: Unexpected token (

SyntaxError, , , .

> (function(x,y) {})
function (x,y) {}

, undefined.

> function a(x,y) {}
undefined

( )

(function a(x,y) {})
function a(x,y) {}

> var x = function(x,y) {}
undefined

( )

> var x;
> (x = function(x,y) {})
function (x,y) {}

. .

+4

, . , (, jQuery).

+1

, . ,

( (h, j) {           //       }) , function myfunc(c, b) {}

+1

Source: https://habr.com/ru/post/1753821/


All Articles