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 .
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 .
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.
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.
Source: https://ru.stackoverflow.com/questions/33173/
All Articles