JavaScript clos...LOGIN

JavaScript closures

What is a closure

Closure, the official explanation of closure is: one that has many variables and binds these variables An expression of the environment (usually a function), so these variables are part of the expression. Characteristics of closure:

 1. As a reference to a function variable, it is activated when the function returns.

 2. A closure is a stack area that does not release resources when a function returns.

Simply put, Javascript allows the use of internal functions---that is, function definitions and function expressions are located in the function body of another function. Furthermore, these inner functions have access to all local variables, parameters, and other inner functions declared in the outer function in which they exist. A closure is formed when one of these inner functions is called outside the outer function that contains them.


Several ways to write and use closures

The first way to write

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
    <script type="text/javascript">  
          function Circle(r) {  
            this.r = r;  
           }  
           Circle.PI = 3.14159;  
           Circle.prototype.area = function() {  
             return Circle.PI * this.r * this.r;  
           }  
          var c = new Circle(1.0);     
           alert(c.area());   
    </script>  
</head>  
<body>  
</body>
</html>

There is nothing special about this way of writing, it just adds some attributes to the function.

The second way of writing

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
    <script type="text/javascript">  
       var Circle = function() {  
         var obj = new Object();  
         obj.PI = 3.14159;  
        obj.area = function( r ) {  
             return this.PI * r * r;  
           }  
            return obj;  
         }  
        var c = new Circle();  
         alert( c.area( 1.0 ) );  
    </script>  
</head>  
<body>  
</body>
</html>

This way of writing is to declare a variable and assign a function as a value to the variable.

The third way of writing

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
    <script type="text/javascript">  
       var Circle = new Object();  
            Circle.PI = 3.14159;  
            Circle.Area = function( r ) {  
             return this.PI * r * r;  
            }  
           alert( Circle.Area( 1.0 ) );  
    </script>  
</head>  
<body>  
</body>
</html>

This method is best understood, which is to create a new object, and then add attributes and method.

The fourth way of writing

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
    <script type="text/javascript">  
         var Circle={  
           "PI":3.14159,  
            "area":function(r){  
               return this.PI * r * r;  
              }  
           };  
          alert( Circle.area(1.0) );  
    </script>  
</head>  
<body>  
</body>
</html>

This method is commonly used and is the most convenient. var obj = {} is to declare an empty object


##The purpose of Javascript closure

In fact, by using closures, we can do a lot of things. For example, it can simulate the object-oriented coding style; express the code more elegantly and concisely; and improve the execution efficiency of the code in some aspects.

1. Anonymous self-executing function

2. Result cache

3. Encapsulation

4. Implementation classes and inheritance


##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:

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

##If we can access plus externally () function, this can solve the counter dilemma.

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

A closure is needed here.

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

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

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

Next Section

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> function buildFunctions(){ var funcArr = []; for(var i = 0; i < 3; i++){ funcArr.push((function(j){ return function(){ console.log(j); }; }(i))); } return funcArr; } var fs = buildFunctions(); fs[0](); //0 fs[1](); //1 fs[2](); //2 </script> </head> <body> <p>请在浏览器中点击 F12 来观察结果</p> </body> </html>
submitReset Code
ChapterCourseware