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

In-depth understanding of umask in new linux file permission settings

Preface The origin is a question 1: If your umask...

JavaScript to achieve fancy carousel effect

This article shares two methods of implementing t...

Vue uses better-scroll to achieve horizontal scrolling method example

1. Implementation principle of scrolling The scro...

Detailed explanation of cocoscreater prefab

Table of contents Prefab How to create a prefab T...

Understanding MySQL index pushdown in five minutes

Table of contents What is index pushdown? The pri...

BUG of odd width and height in IE6

As shown in the figure: But when viewed under IE6...

Summary of Docker Data Storage

Before reading this article, I hope you have a ba...

960 Grid System Basic Principles and Usage

Of course, there are many people who hold the oppo...

Introduction to Spark and comparison with Hadoop

Table of contents 1. Spark vs. Hadoop 1.1 Disadva...

Detailed description of ffmpeg Chinese parameters

FFMPEG 3.4.1 version parameter details Usage: ffm...

CSS sets the list style and creates the navigation menu implementation code

1. Set the list symbol list-style-type: attribute...

A possible bug when MySQL executes the sum function on the window function

When using MySql's window function to collect...

Summary of several error logs about MySQL MHA setup and switching

1: masterha_check_repl replica set error replicat...

Front-end vue+express file upload and download example

Create a new server.js yarn init -y yarn add expr...