Javascript closure and scope
Today we will talk about the use of javascript scopes and closures. Let's first talk about the concept of scope. Various Development Speech will encounter the life cycle of variables. The scope of use is actually the scope of variables. Literally, this variable is valid within that code range.
1. The Javascript scope is the function scope rather than the block-level scope. Check the Code:
(Function () {var I = 1; if (I = 1) {var j = 3;} console. log (j); // can be accessed here })()
Here, j is accessible, that is, variables defined at any position in a function are visible anywhere in the function. Let's look at another situation:
function a(){ function b(){ //code }}
The variables declared in method a can also be used in method B. The principle is the same as above.
2. The scope of variables in Javascript is divided into global variables and local variables. See the Code:
var p=11;function f1(){ console.log(p);}f1(); //11
The variable declared outside the method body is a global variable, which can be accessed in any method. Let's look at another global variable declaration method:
function f1(){ p=11;}f1();console.log(p);
Since p = 11 is declared in the method body, it is equivalent to having the global variable p, so this declaration method is also acceptable, but it is not recommended.
3. How can I access and operate the variables in the function? Here we need to use closures.
Let's take a look at the official explanation of the closure:A closure is an expression (usually a function) that has many variables and is bound to these variables. Therefore, these variables are part of the expression.
I can't help but ask, what is this?
Later, I started to understand it by referring to some blogs and "Javascript Secret Garden". The closure is probably because a function inside the function is called externally, so that internal variables can be called. For example, the following section
function f1(){ var p=11; return { increment: function() { p++; }, show: function() { alert(p) } }}var f=f1();f.show(); //11f.increment();f.show(); //12
This method is similar to the get set Method for private variables in java bean.