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

JavaScript imitates Jingdong magnifying glass special effects

This article shares the specific code of JavaScri...

Detailed installation tutorial of zabbix 4.04 (based on CentOS 7.6)

1. Preparation before installation: 1.1 Install J...

Several ways to clear arrays in Vue (summary)

Table of contents 1. Introduction 2. Several ways...

TypeScript interface definition case tutorial

The role of the interface: Interface, in English:...

Example code of implementing starry sky animation with CSS3 advanced LESS

This article introduces the sample code of advanc...

Detailed explanation of keywords and reserved words in MySQL 5.7

Preface The keywords of MySQL and Oracle are not ...

Introduction and analysis of three Binlog formats in MySQL

one. Mysql Binlog format introduction Mysql binlo...

JS implements the sample code of decimal conversion to hexadecimal

Preface When we write code, we occasionally encou...

JS implements a detailed plan for the smooth version of the progress bar

The progress bar is not smooth I believe that mos...

Nexus uses API to operate

Nexus provides RestApi, but some APIs still need ...

Basic statements of MySQL data definition language DDL

MySQL DDL statements What is DDL, DML. DDL is dat...

MySQL trigger trigger add, delete, modify and query operation example

This article uses examples to describe the add, d...

Solve the problem that ifconfig and addr cannot see the IP address in Linux

1. Install the Linux system on the virtual machin...