JavaScript Closures Explained

JavaScript Closures Explained

1. What is a closure?

A combination of the function itself and the state of the environment in which the function is declared.

1.2 Memoization of closures: functions remember the environment in which they were defined

1.3 Closure phenomenon: closure is created every time a function is created in JS

2. Functions of closures: memorization, simulation of private variables

2.1 Memory

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        function createCheckTemp(standardTemp){
            function checkTemp(n){
                if(n<=standardTemp){
                    alert('Your temperature is normal');
                }else{
                    alert('Your body temperature is high');
                }
            }
            return checkTemp;
        }
        var checkTemp_A = createCheckTemp(37.1);
        var checkTemp_B = createCheckTemp(37.3);
        checkTemp_A(37.2);
        checkTemp_A(37.0);
        checkTemp_B(37.2);
        checkTemp_B(37.0);
    </script>
</body>
</html>

detail:

1: Memory of closures

2: The function return checkTemp is a function name

3: Define var checkTemp_A and checkTemp_A to get the function name checkTemp instead of calling it directly

2.2 Simulating private variables (secure variables)

Closure code example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // Encapsulate a function, the function of this function is to privatize the variable function fun(){
            // Define a local variable a
            var a=0;
            return {
                getA:function(){
                    return a;
                },
                add:function(){
                    a++;
                },
                pow:function(){
                    a*=2;
                }
            }
        }
        var obj = fun();
        // If you want to use variable a outside the fun function, the only way is to call the getA() method console.log(obj.getA());
        // Want to add 1 to variable a obj.add();
        obj.add();
        obj.add();
        console.log(obj.getA());
        obj.pow();
        console.log(obj.getA());
    </script>
</body>
</html> 

In fact, it is understandable that JavaScript cannot define function types like C++ and Java, such as int sum(), int add(), int pow(), etc., so it is necessary to use the characteristics of closures: that is, to use the memory of the closure within the function to operate on the variables within the function, and then return the name of the closure function to perform internal data operations.

3.IIFE (Immediately Invoked Function Expression):

JS special function, once defined, is called immediately

3.1 IIFE role 1- assigning values ​​to variables

Example:

Compare the before and after pictures to reflect the programming level. . . Simplify the code. . Beautiful. . .

3.2 IIFE Function 2-Converting Global Variables into Local Variables

In this case, the results of the following five statements are all 5, because there is no concept of block scope in JS (this is the understanding for now), so var i becomes a global variable, and i=5 after the for loop. So the results of all five statements are 5.

Then we can use IIFE to solve this problem, which essentially uses the closure feature of the function.

By passing the global variable i into the IIFE function, the global variable becomes a local variable. By using the closure feature of the JS function , the function of arr[2]() in the figure can be implemented.

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • JavaScript Advanced Closures Explained
  • JavaScript Closures Explained
  • Javascript scope and closure details
  • Detailed explanation of JavaScript closure issues
  • Detailed explanation of Javascript closures and applications
  • Detailed explanation of js closure and garbage collection mechanism examples
  • Analysis of JS closure principle and its usage scenarios
  • Detailed explanation of the principle and function of JavaScript closure

<<:  CSS fixes the container level (div...) tag in one position (on the far right of the page)

>>:  Before making a web page, let’s take a look at these so-called specifications

Recommend

HTML form tag tutorial (2):

This tutorial introduces the application of vario...

DHTML objects (common properties of various HTML objects)

!DOCTYPE Specifies the Document Type Definition (...

Beginners learn some HTML tags (1)

Beginners can learn HTML by understanding some HT...

JDBC Exploration SQLException Analysis

1. Overview of SQLException When an error occurs ...

MySQL online log library migration example

Let me tell you about a recent case. A game log l...

How to run nginx in Docker and mount the local directory into the image

1 Pull the image from hup docker pull nginx 2 Cre...

In-depth understanding of the use of r2dbc in MySQL

Introduction MySQL should be a very common databa...

Docker meets Intellij IDEA, Java development improves productivity tenfold

Table of contents 1. Preparation before developme...

CentOS 6 uses Docker to deploy Zookeeper operation example

This article describes how to use docker to deplo...

HTML+Sass implements HambergurMenu (hamburger menu)

A few days ago, I watched a video of a foreign gu...

Why is IE6 used by the most people?

First and foremost, I am a web designer. To be mor...

Example of ellipsis when CSS multi-line text overflows

Ellipses appear when multi-line text overflows Th...

Ubuntu opens port 22

Scenario You need to use the xshell tool to conne...