What is closure

Time:2020-11-7

Today is the second part of the series, mainly about closure related issues.
In my opinion, the issue of closure is actually the issue of scope, so I will start with the issues related to scope.

What is scope?

Scope is the management scope that the variable can access (or the management scope of the variable). For example: class to prepare for the cleaning, the monitor to the class on duty to arrange cleaning tasks. Xiao Ming is responsible for cleaning the toilet, Xiao Hong and Xiao Ding are responsible for cleaning the classroom, and Xiao Long is responsible for cleaning the playground. Then we can say that Xiao Ming’s scope of management is the toilet area, and Bruce Lee’s management scope is the playground area; in other words, Xiao Ming’s scope is toilet, and Bruce Lee’s scope is playground.

General scope can be divided into lexical scope (also called static scope) and dynamic scope, while in JS, lexical scope is generally used.

What is lexical scope?

Let’s first give a definition: lexical scope is a variable or function. When defining, it confirms its management scope and will not change. < span style = “color: red;” > to sum up, you can access what the function sees. < / span > the concept of dry looks boring? Take an example

function a(x){
    var y = x + 4
    function fn(z){
        console.log(z)
    }
    fn(10 * y)
}
a(4) //80
console.log(y) //y is not defined

The above is an example of a very general scope. The output value of a (4) is 80, and an error is reported when y is output. The error message is that the variable y is not found. Let’s analyze this code with the knowledge of scope:

  • Global scope:
  • Function a scope: X, y
  • Function fn scope: Z

Therefore, we can see that the management range of variable y is in function a, but the value of Y output in the global scope is obviously not in its management scope, so an error is reported (the variable cannot be found).
There is also a very important knowledge point here, which is the life cycle of variables.

What is the life cycle of a variable?

Let’s compare variables with human beings. For example, human life cycle refers to the whole process from birth to death. Therefore, the life cycle of a variable is the process from its creation to its death. From the life cycle of variables, it can be divided into global scope and function scope. First give them a definition:

global scope

The scope of a variable is global, which is called global scope.

Function scope

Variables defined only in the body of a function are called function scopes

In the above example, we can see that variables are in the global scope and function scope. What kind of process will the variables in the global scope and function scope go through in the process of program running?

  • Once the variables in the global scope are defined, they will be saved in memory until the program stops unless they are destroyed actively.
  • Variables in the scope of a function are destroyed after they leave the function during the function run.

So we can’t find the variable y in the global scope because after the a function is executed, the variable y does not exist. However, there is a way to realize that variables in function scope can not be destroyed after leaving function, that is closure.

What is closure?

After thousands of calls, I finally saw the protagonist of this article. As mentioned above, to realize the function of accessing variables in the function scope after leaving the function, the closure is introduced. Let’s not talk about how to realize the function of closure. Let’s define it first.

The popular definition on the Internet is: a function that can access the internal variables of other functions. I have compared some other statements, and this one is more reliable. This is related to the requirement that variables in the scope of the function can be accessed after leaving the function. So how does it work? Look at chestnuts

function fn(){
    var a = 10
    return function say(b){
        console.log(a + b)
    }
}
var getVal = fn()
getVal(5)

This is a very typical closure writing method: the function returns a declared function within a function. After FN is executed, the return value is assigned to getval, and then getval is executed. We can see that the function say is executed when getval is executed, and the scope of the function say is determined when it is declared. We can see that its lexical scope has permission to access a and B variables. Finally, print the value of a + B and print out 15.

Therefore, the closure here is actually doing such a thing: after executing the FN function, it still has the ability to save variable a in memory, so that the life cycle of variable a is always stored in memory like the global variable. However, variable a is private. It can only be accessed by the function getval. It is not like other global variables that can be accessed and modified at will. Naturally, we can see that closures have such advantages.

Advantages of closures

  • You can continue to access the function’s variables after leaving the function, and the variables are always stored in memory.
  • Variables in closures are private, and only closure functions have access to them. It will not be contaminated by external variables and methods.

Common usage of closures

  • Using modular packaging

Here is index.js Reference the content of m.js module

//File: m.js
(function(){
    var name ='Lucy'
    var getName = function(){
        ...
    }
    exports.mode = {
        name,
        getName
    }
})()

//Documents index.js
var {mode} = require('./m.js')
mode.getName()
  • Mimic block level scope
//Before transformation: output 5 5
for(var i=0; i<5; i++){
    console.log(i)
}

//After transformation: output 0-4
for(var i=0; i<5; i++){
    (function(j){
        console.log(j)
    })(i)
}

The defect of closure

  • It will increase the usage of memory and affect the performance
  • Improper use of closures can cause memory leaks

summary

Review the main contents of this chapter

  • Scope: refers to the scope of management that variables can access. It is easier to understand when combined with regional management in life.
  • Lexical scope: when a variable is defined, its management scope is determined, and it will not change again.
  • Life cycle of variables: the process from birth to destruction of variables

    • Global scope: global scope
    • Function scope: variables are defined only in the body of a function
  • Closure: a function that can access variables inside other functions
  • The essence of a closure is to assign a value to a variable when the internal function is returned by the executing function. According to the lexical scope, variable a has the same permissions as the internal function to access the variables in its scope. Therefore, the variables in the closure are not destroyed and are still stored in memory, thus realizing the access of external functions to internal variables.

There are also some knowledge points in this paper, such as variable recycling, scope chain, execution context, variable promotion and so on. Because of the space problem, there is no detailed expansion, which will be supplemented in the later stage.

Reference articles

  • https://juejin.im/post/5afb0a…
  • https://juejin.im/post/5b081f…
  • https://segmentfault.com/a/11…
  • https://www.jianshu.com/p/6c6…