Because JavaScript does not have the concept of block-level scopes, the variables defined in the block statement are actually created in the include function rather than in the statement.
Such as:
function Outputnumbers (count) {for (var i=0; i< count; i++) { alert (i); } alert (i);}
A For loop is defined in this function, and the initial value of the variable i is set to 0. In Java, C + + and other languages, the variable i is only defined in the statement block for the For loop, and once the loop is finished, the variable i is destroyed. But in JavaScript, the variable i is defined in the Outpunumbers () activity object, so it is possible to follow it within the function from the beginning of its definition. Even if the same variable is declared again and again, as in the following, it does not change its value.
function Outputnumbers (count) {for (var i=0; i< count; i++) { alert (i); } var i; Declare variable alert (i) again; Count
JavaScript never tells you whether the same variable is declared more than once; in such a case, it ignores the subsequent declaration, but runs the variable initialization in the May declaration. Anonymous functions can be used to mimic block-level scopes and avoid this problem.
(function () { //This is a block-level scope}) ()
The above code defines and immediately invokes an anonymous function. A function declaration is included in a pair of parentheses to indicate that it is actually a function expression. And then there's a pair of parentheses that immediately call this function,
The second method:
var someFunction = function () { //This is a block-level scope};somefunction ();
The example above defines a function and then calls it immediately. The way to define a function is to create an anonymous function and assign the anonymous function to the variable somefunction. The way to call a function is to add a pair of parentheses after the function name, but it is important to note that the function value does not replace the function name, as
function () { //This is a block-level scope} ();
This results in a syntax error because JavaScript treats Functionkeyword as the beginning of a function declaration, and the function declaration cannot have parentheses after it. After expression can be followed by parentheses
Javascirpt How to mimic block-level scopes (JS elevation notes)