JavaScript closures



JavaScript variables can be local variables or global variables.

Private variables can use closures.


Global variables

Functions can access variables defined within the function, such as:

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<p>函数可以访问函数内部定义的变量:</p>
<button type="button" onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction() {
    var a = 4;
    document.getElementById("demo").innerHTML = a * a;
} 
</script>

</body>
</html>

Run Example»

Click the "Run Example" button to view the online example

The function can also access variables defined outside the function, such as:

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<p>函数可以访问定义在函数外的变量:</p>
<button type="button" onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
var a = 4;
function myFunction() {
	document.getElementById("demo").innerHTML = a * a;
} 
</script>

</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance

The next one In the 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.

NoteThe variable declaration is a global variable if the var keyword is not used, even if it is defined within the function.

Variable life cycle

The scope of global variables is global, that is, global variables are everywhere in the entire JavaScript program.

The variables declared inside the function only work inside the function. These variables are local variables and their scope is local; the parameters of the function are also local and only work inside the function.


Counter Dilemma

Imagine if you want to count some values, and the counter is available in all functions.

You can use global variables, functions to set the counter increment:

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<p>全局变量计数。</p>
<button type="button" onclick="myFunction()">计数!</button>
<p id="demo">0</p>
<script>
var counter = 0;
function add() {
    return counter += 1;
}
function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

</body>
</html>

Run instance»

Click the "Run Instance" button to view the online instance

The counter value changes when the add() function is executed.

But here comes the problem, any script on the page can change the counter, even if the add() function is not called.

If I declare a counter within a function, the value of the counter cannot be modified without calling the function:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<p>局部变量计数。</p>
<button type="button" onclick="myFunction()">计数!</button>
<p id="demo">0</p>
<script>
function add() {
    var counter = 0;
    return counter += 1;
}
function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance

The above code will not be output correctly. Every time I call the add() function, the counter will be set to 1.

JavaScript inline functions can solve this problem.


JavaScript embedded functions

All functions can access global variables.

In fact, in JavaScript, all functions can access the scope above them.

JavaScript supports nested functions. Nested functions can access the function variables of the upper level.

In this example, the embedded function plus() can access the counter variable of the parent function:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<p>局部变量计数。</p>
<p id="demo">0</p>
<script>
document.getElementById("demo").innerHTML = add();
function add() {
	var counter = 0;
    function plus() {counter += 1;}
    plus();    
    return counter; 
}
</script>

</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance

If we can access it externallyplus( ) function, thus solving the counter dilemma.

We also need to ensure that counter = 0 is executed only once.

We need closures.


JavaScript Closure

Remember the function calling itself? What does this function do?

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<p>局部变量计数。</p>
<button type="button" onclick="myFunction()">计数!</button>
<p id="demo">0</p>
<script>
var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();
function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

</body>
</html>

Run instance »

Click the "Run instance" button to view the online instance

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 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.

NoteA closure is a function that can access variables in the scope of the upper-level function, even if the upper-level function has been closed.