JS-scope division, js-Domain Division
Which of the following cannot be used in other languages,Js scopes are divided by functions.Unlike C, java, and other advanced languages, there is a strict distinction between block-level scopes. in java, for or if is regarded as an independent block-level scope, however, curly braces in the if and for statements in JavaScript are not independent scopes. The JavaScript scope is entirely determined by the function. For example
If (true) {var name = 'hangsan';} console. log (name); // output zhangsan
The above code will produce an undefined variable error in C and java, because if (true) {...} in Java ){...} is an independent scope. variables defined in if cannot be accessed outside if. However, if is not an independent scope in js, therefore, you can access the local variable name outside the if clause. for example, the following code:
Function test () {for (var I = 1; I <5; I ++) {alert (I);} alert ("the value of external call I is: "+ I); // The external call I value is 5}
You can also access the local variable I outside the for loop, so you also want to implement the effect in java in js: "variable I cannot be accessed outside the for loop after the for loop ends. Can it be implemented ???
The answer is: yes, of course !!
How can this problem be achieved ?? You need to use the self-executed function expression in JavaScript. If you do not understand the function expression and self-execution, please refer to my other article "js function declaration and function expression".
(function(){ for(var i=1;i<5;i++){ alert(i); }})();
This is a self-executed function expression.
Function test () {(function () {for (var I = 1; I <5; I ++) {alert (I );}})(); alert ("the value of external call I is:" + I); // if this is re-access I, the access fails} test ();
In this case, when I is accessed outside the for loop, an I-defined error is returned.
We can see that:In js, if you want to make local variables in a piece of code not accessed outside of this code, you can implement them through self-executed function expressions; this can avoid conflicts with external code.
In other words, you can use self-executed function expressions in JavaScript to implement block-level scopes in java and other advanced languages.