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

6 Ways to Elegantly Handle Objects in JavaScript

Table of contents Preface 1. Object.freeze() 2. O...

Detailed explanation of how to configure openGauss database in docker

For Windows User Using openGauss in Docker Pull t...

Solution to the CSS height collapse problem

1. High degree of collapse In the document flow, ...

React diff algorithm source code analysis

Table of contents Single Node Diff reconcileSingl...

Based on the special characters in the URL escape encoding

Table of contents Special characters in URLs URL ...

uniapp implements date and time picker

This article example shares the specific code of ...

Graphical tutorial on installing JDK1.8 under CentOS7.4

Linux installation JDK1.8 steps 1. Check whether ...

CocosCreator implements skill cooling effect

CocosCreator realizes skill CD effect There are s...

Detailed explanation of the use of Refs in React's three major attributes

Table of contents Class Component Functional Comp...

Html to achieve dynamic display of color blocks report effect (example code)

Use HTML color blocks to dynamically display data...

MySQL fuzzy query usage (regular, wildcard, built-in function)

Table of contents 1. MySQL wildcard fuzzy query (...

A preliminary understanding of CSS custom properties

Today, CSS preprocessors are the standard for web...

MySQL View Principle Analysis

Table of contents Updatable Views Performance of ...