Excerpt from: http://outofmemory.cn/wr/?u=http%3A%2F%2Fwww.phpvar.com%2Farchives%2F3033.html
JS does not have block-level scopes, simple examples:
for (var i=0;i<10;i++) {alert (i);} alert (i);
For Loop I, in other languages like C, In Java , it is destroyed at the end of the for, but JS can still access the I value in subsequent operations, that is, alert (i) after the for loop; the value i=10 will pop up ;
JS mimics block-level scopes:
(function() {for (var i=0;i<10;i++) {alert (i);}}) (); alert (i);
JS Private scope (mimic block-level scope) syntax format:
(function() {/// This is block-level scope // action: Restrict adding too many variables and functions to the global scope, That is, avoid internal temporary variables affecting the global Space });
The function declaration is included in a pair of (), which means that the function is actually a function expression (note: The function expression can be followed by (), to convert the function declaration into a function expression, simply by () the function declaration is included), and immediately after the other pair () will call the function.
therefore (function () {}) (); Can be understood to define a function expression, and immediately call the function expression, that is, the equivalent of defining:
var somefunction=function() {} ()
Or
var somefunction=function() {};somefunction ();
It is notable that (function () {}) (); followed by a semicolon, without this semicolon, (function () {}) () The code behind the error! This, combined with the semicolon at the back of the function expression above, will explain why you should take this semicolon.
(function () {}) () the 2nd bracket can take multiple parameters, such as:
(function(ARG1,ARG2) {}) (ARG1,ARG2);
Or
var somefunction=function(arg1,arg2) {} (ARG1,ARG2);
If the 2nd bracket has parameters, then the function must be called with the corresponding parameters, otherwise it will error, such as:
SomeFunction () Error without parameters: Uncaught typeerror:undefined is not a function
JS Private scope (function () {}) (); Mimic block-level scopes