javascript b package refers to closure, and closure is an important concept in Javascript. It is a mechanism to protect private variables. It forms a private scope when the function is executed and protects the private variables inside. Free from outside interference.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
What is the javascript b package?
JavaScript Closures
JavaScript variables can be local variables or global variables.
Private variables can use closures.
Global variables
The function can access variables defined inside the function, such as:
Instance
function myFunction() { var a = 4; return a * a; }
The function can also access variables defined outside the function, For example:
Example
var a = 4; function myFunction() { return a * a; }
In the following example, a is a global variable.
Global variables in web pages belong to the window object.
Global variables apply to all scripts on the page.
In the first instance, a is a local variable.
Local variables can only be used inside the function in which they are defined. Not available for other functions or script code.
Even if global and local variables have the same name, they are two different variables. Modifying one of them will not affect the value of the other.
Note If the var keyword is not used when a variable is declared, it is a global variable, even if it is defined within a function.
JavaScript Closure
Remember the function calling itself? What does this function do?
Example
var add = (function () { var counter = 0; return function () {return counter += 1;} })(); add(); add(); add(); // 计数器为 3
Example analysis
Variable add specifies the return word value of the function self-call.
The self-calling function is only executed once. Set counter to 0. and returns the function expression.
add variable can be used as a function. The cool part is that it gives access to counters from the scope above the function.
This is called a JavaScript closure. It makes it possible for functions to have private variables.
The counter is protected by the scope of the anonymous function and can only be modified through the add method.
Note
Closure is a mechanism to protect private variables. It forms a private scope when a function is executed and protects the private variables inside from external interference.
Intuitively speaking, it is to form a stack environment that is not destroyed.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of What is javascript b package. For more information, please follow other related articles on the PHP Chinese website!