question? What is the closure principle of js (javaScript) and what is its function?
1. Definition
Official explanation: A closure is an expression that has many variables and an environment that binds these variables (usually is a function), so these variables are also part of the expression.
Obviously, ya. . . . . What! Rural people can’t understand the door-smashing! ! !
So the editor’s understanding is this: **** is a function defined in a function and can be accessed externally. (Under normal circumstances we cannot access local functions)This is a bit like taking off your pants and farting. It is unnecessary, but it is not unnecessary. Closures definitely have their uses.
2. Prevent modifiable variables, because internal variables are inaccessible from the outside and cannot be modified. Safety
3. Read the variables inside the function. The other is to keep the values of these variables in the memory.
2. Example: (js code)1. The special thing about Javascript language is that the global function can be read directly inside the function variable.
var n=999;
function f1(){
alert(n);
}
f1(); // 999
2. On the other hand, local variables within the function cannot be read outside the function. function f1(){
var n=999;
}
alert(n); // error
There is one thing to note here. When declaring variables inside a function, you must use the var command. If you don't use it, you are actually declaring a global variable!
function f1(){
n=999;
}
f1();
alert(n); // 999
##**** *How to read local variables from outside?
#We sometimes need to get local variables within a function. However, as mentioned before, this is not possible under normal circumstances and can only be achieved through workarounds.
##
function f1(){ n=999; function f2(){ alert(n); // 999 } }
3. Use closure Notes on packages
#2) The closure will change the value of the variable inside the parent function outside the parent function. Therefore, if you use the parent function as an object, the closure as its public method, and the internal variables as its private value, you must be careful not to Feel free to
The above is the understanding of the closure principle of js. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com )!