Implementation principle and function of Js closure

Implementation principle and function of closure

1. The concept of closure: refers to a function that has access to variables in the scope of another function. Generally, one function contains another function.

2. The function of closures: access the internal variables of functions, keep the functions existing in the environment, and will not be handled by garbage collection mechanism

Because the variables declared inside the function are local and can only be accessed inside the function, but the variables outside the function are visible inside the function, which is the characteristic of scope chain.

The child can find variables from the parent level and find them level by level until they are found

function  bar(){
        //Variables declared by the outer function
        var value=1;

        function foo(){
            console.log(value);
        }
        return foo();
    };
    var bar2=bar;
    //In fact, the bar() function is not disposed of by the garbage collection mechanism after execution
    //This is the function of closures. When you call the bar() function, you will execute the foo function inside, and foo will access the variables in the outer layer
    bar2();

Therefore, we can create another function inside the function, so that the variables of the outer function are visible to the internal function, and then we can access its variables.

3. Advantages of closures:

  • Facilitate the invocation of local variables declared in the context
  • The logic is tight. You can create another function in a function to avoid the problem of parameter transmission

4. Disadvantages of closures:

Because the use of closures can make the function not be destroyed after execution and kept in memory. If closures are used heavily, it will cause memory leakage and consume a lot of memory

 

Application of js closure in practical development

1. Use variables inside a function outside a function Function as the return value (closure function: to prevent variables from being polluted by the environment)

function F1(){
  var a = 100;
    return function(){
      console.log(a)    
    }
}
var f1 =F1();
var a = 200;
f1()//100
function init(){
    var name = "hello world";//name is a local variable created by init
    function sayName(){//sayName is an internal function, closure
        alert(name);//Variable name declared with parent function
    }
    sayName();
}
init();//"hello world"

 

2. Pass function as parameter

function F1(){
   var a = 100;
    return function(){
      console.log(a)    
    }
}
var f1 =F1();
function F2(fn){
  var a = 200;
     fn();
}
F2(f1);  // 100

 

3. Associate a function with some data it operates on. Usually, you can use closures wherever you use an object with only one method

// Change dom style
document.getElementById("a").onclick = setSize(12);
    document.getElementById("b").onclick = setSize(18);
    document.getElementById("c").onclick = setSize(22);
    function setSize(fontSize){
        return function(){
            document.body.style.fontSize = fontSize + 'px';
        }
    }

 

4. Simulate private methods with closures

//These three common functions are closures that share the same environment. Thanks to the lexical scope of JavaScript, they can access the privateCounter variable and the changeBy function.
var makeCounter = function () {
        var privateCounter = 0;
        function changeBy(val){
            privateCounter += val;
        };
        return {
            increment: function(){
                changeBy(1);
            },
            decrement: function(){
                changeBy(-1);
            },
            value: function(){
                return privateCounter;
            }
        }
    };
    var Counter1 = makeCounter();
    var Counter2 = makeCounter();
    Counter1.increment();
    console.log(Counter1.value());//Each time one of the counters is called, the lexical environment of the closure will be changed by changing the value of this variable. However, the modification of variables in one closure will not affect the variables in another closure.
    console.log(Counter2.value());//Using closures in this way provides many benefits related to object-oriented programming -- especially data hiding and encapsulation.

Resource search website Encyclopedia https://www.renrenfan.com.cn Guangzhou VI design companyhttps://www.houdianzi.com

5. Closure in loop

How can we achieve output 0-5?

for (var i = 0; i < 5; i++) {
   setTimeout(function () {
    console.log(i);
  }, 1000 * i);
}//55555
//Method 1: the makeCallback function creates a new lexical environment for each callback.
function makeCallback(i) {
     return function() {
        console.log(i)
      };
    }
    for(var i=0;i<10;i++){
        setTimeout(makeCallback(i),1000)
    }
//Another method uses anonymous closures
for(var i=0;i<10;i++){
        (function(i){
            setTimeout(function () {
                console.log(i)
            },1000)
        })(i)
    }
//Declare variables using let
for (let i = 0; i < 5; i++) {
  setTimeout(function () {
    console.log(i);
  }, 1000 * i);
}

Tags: Javascript

Posted by SnakeO on Tue, 03 May 2022 03:36:57 +0300