Often seen when the JavaScript code turns into this structure:

(function(){ // ... код ... })(); 

What is it for? An example of one of these libraries can be found here .

    2 answers 2

    This is called "closure" and is used to create your own namespaces. More details can be read on javascript Garden . Often this property is used to run on an array:

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

    In this case, each link will produce a window with the number of links (i = a.length).

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

    And in this case, a closure is created, and the value n is not taken from the outside. That is, the links will give out when clicking a serial number.

    • one
      Thanks for the link to the site - yozh
    • one
      You are not quite right, it will be a closure only if you leave a link to an internal variable somewhere in an external context. In this case, this is most likely a simple trick, but not to litter the global NS. - timka_s

    Calls the function immediately after the declaration.
    so-called "immediate call of the declared function", if you take tracing from English.
    Equivalent to:

     function abc(){ //something; } abc(); 

    well, and it is necessary that it was possible to use this piece independently, incl. control of visibility area so that when you insert it into someone else's code, it will suffer as little as possible.

    • It's clear! But, if the code is not wrapped, it will also be executed ... - KiTE
    • See addition. =) It is useful, for example, when trying to create a singleton. - knes
    • I understand that this is a kind of screening of local variables? .. - KiTE
    • Including. Let's just say that it is for this reason that it is most often used, for example, by inserting third-party counters on the page - knes