Javascript closure usage scenario principle detailed

Javascript closure usage scenario principle detailed

1. Closure

In Javascript , only sub-functions inside a function can read local variables, and closures are functions that can read variables inside other functions.

For example, the following code:

function f1() {
    var n = 999;
    function f2() {
    console.log(n);
    }
    return f2;
}
var result = f1();
result();//999

Function f2 is included in function f1, and all local variables in f1 are visible to f2. But the reverse is not true. The local variables inside f2 are not visible to f1.

This is the " chain scope scope" structure unique to the Javascript language. Child objects will search for variables of all parent objects one level at a time. Therefore, all variables of the parent object are visible to the child object, but not vice versa.

Since f2 can read the local variables in f1, as long as f2 is used as the return value, its internal variables can be read outside f1.

2. Closure usage scenarios

1.setTimeout

The first function passed by the native setTimeout cannot have parameters, and the parameter passing effect can be achieved through closure.

function f1(a) {
    function f2() {
        console.log(a);
    }
    return f2;
}
var fun = f1(1);
setTimeout(fun,1000);//Print out 1 after one second

2. Callback

Define a behavior and associate it with a user event (click or keypress). Code is usually bound to an event as a callback (a function that is called when the event is triggered).

For example, the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
    <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="size-12">12</a>
    <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="size-20">20</a>
    <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="size-30">30</a>

    <script type="text/javascript">
        function changeSize(size){
            return function(){
                document.body.style.fontSize = size + 'px';
            };
        }

        var size12 = changeSize(12);
        var size14 = changeSize(20);
        var size16 = changeSize(30);

        document.getElementById('size-12').onclick = size12;
        document.getElementById('size-20').onclick = size14;
        document.getElementById('size-30').onclick = size16;

    </script>
</body>
</html>

When you click on a number, the font size will change to the corresponding size.

3. Function anti-shake

The callback is executed n seconds after the event is triggered. If it is triggered again within n seconds, the timing is restarted.

The key to the implementation lies in the setTimeOut function. Since a variable is needed to save the timing, in order to maintain global purity, it can be implemented with the help of closures.

As shown in the following code:

/*
* fn [function] the function that needs anti-shake* delay [number] milliseconds, anti-shake deadline value*/
function debounce(fn,delay){
    let timer = null
    //With the help of closure return function() {
        if(timer){
            clearTimeout(timer) //Entering this branch statement indicates that a timing process is currently in progress and the same event is triggered again. So to cancel the current timing and restart the timing timer = setTimeOut(fn,delay) 
        }else{
            timer = setTimeOut(fn,delay) // Entering this branch means that there is no timing currently, so start a timing}
    }
}

4. Encapsulate private variables

As shown in the following code: Create a counter using js

Method 1:

function f1() {
    var sum = 0;
    var obj = {
       inc:function () {
           sum++;
           return sum;
       }
};
    return obj;
}
let result = f1();
console.log(result.inc());//1
console.log(result.inc()); //2
console.log(result.inc());//3

In the returned object, a closure is implemented, which carries the local variable x, and the variable x cannot be accessed from external code at all.

Method 2:

function f1() {
    var sum = 0;
    function f2() {
        sum++;
        return f2;
    }
    f2.valueOf = function () {
        return sum;
    };
    f2.toString = function () {
        return sum+'';
    };
    return f2;
}
//Execute function f1, and return function f2
console.log(+f1());//0
console.log(+f1()()) //1
console.log(+f1()()()) //2


All js data types have the two methods valueOf and toString , except null

  • valueOf() method: returns the primitive value of the specified object.
  • toString() method: returns a string representation of the object.

In numerical operations, valueOf is called first, and in string operations, toString is called first.
sum+' ' is a string type data

This is the end of this article about the usage scenarios of Javascript closures. For more relevant Javascript closure content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • 9 usage scenarios of js closures
  • Analysis of JS closure principle and its usage scenarios

<<:  Tudou.com front-end overview

>>:  What is Software 404 and 404 Error and what is the difference between them

Recommend

JavaScript manual implementation of instanceof method

1. Usage of instanceof instanceof operator is use...

Detailed explanation of basic concepts of HTML

What is HTML? HTML is a language used to describe...

MySQL 8.0.22 installation and configuration method graphic tutorial

This article records the installation and configu...

Sharing several methods to disable page caching

Today, when developing, I encountered a method wh...

Linux echo text processing command usage and examples

The description of echo in the Linux help documen...

WeChat Mini Program Lottery Number Generator

This article shares the specific code of the WeCh...

Detailed explanation of the use of title tags and paragraph tags in XHTML

XHTML Headings Overview When we write Word docume...

Two types of tab applications in web design

Nowadays, tabs are widely used in web design, but...

Docker online and offline installation and common command operations

1. Test environment name Version centos 7.6 docke...

How to use Greek letters in HTML pages

Greek letters are a very commonly used series of ...

Detailed explanation of Vue's ref attribute

Summarize This article ends here. I hope it can b...