in other languages, thescope of JS is divided by functions , unlike the C language, Java and other high-level languages, there is a strict block-level scope of the distinction, in Java for or if are considered a separate block-level scope, In JavaScript, however, curly braces in the IF, for statements are not separate scopes. The scope of JavaScript is entirely determined by the function . like
if (true) { var name = ' Zhangsan ';} Console.log (name); Output Zhangsan
The above code will appear in the C language and Java in the variable undefined error, because in Java if (true) {...} is a separate scope, the variable defined in the if is not accessible outside of the IF, but the if is not a separate scope in JS, so the local variable name can still be accessed outside of the IF. In the code such as the following:
function test () {for (Var i=1;i<5;i++) {alert (i);} Alert ("The value of external call I is:" + i); the value of external call I is 5}
also in forLocal variables can still be accessed outside the loopI, then inJSalso want to achieveJavain the effect: "Want to let forvariable after loop endIwill not be able to forout-of-loop access. Can it be achieved???
The answer is: Of course!!
How to achieve that?? You need a self-executing function expression in JavaScript, and if you don't understand what the function expression and self-executing are going to do, refer to my other article, "JS function declaration and function Expression "
(function () {for (var i=1;i<5;i++) { alert (i);
It's a self-executing function expression.
function test () { (function () {for (var i=1;i<5;i++) { alert (i); } }) (); Alert ("The value of external call I is:" + i);//This is the re-access I, the access to the } test ();
Here again forthe outside of the loop in the accessIon the reportIundefined error.
Thus : in js , If you want a piece of code in a local variable, outside of this code is not accessed, it can be implemented by self-executing function expressions, which often can avoid conflicts with external code.
In other words, a self-executing function expression in JS can be used to implement block-level scopes in high-level languages such as Java.
js-Scope Division