Got it

[ Technical Dry Goods ] Deep understanding of closures

Latest reply: Mar 30, 2021 02:09:08 117 1 0 0 0

Hello, everyone!

Today I'm going to introduce you DAYU


Let’s not talk about what a closure is. Let’s first understand the concept of js scope, scope, which is simply to define a variable, in which scope we can use it,

var a = 1;function fn() {
    var b = 2;
    console.log(a);
    console.log(b);}fn();        // 1  2

The above is a simple example, a is a global variable, b is a variable in the scope of the function fn, and js is a chain scope. When a variable is used, it will look up the scope of the variable. Therefore, the values of a and b can be printed inside the function. on the contrary,

var a = 1;function fn() {
    var b = 2;}console.log(a);    // 1console.log(b);    // 报错 b is not defined

Variables in the fn scope cannot be accessed in the global scope.

How does a closure exist? It breaks the constraint that "the variable inside the function cannot be accessed outside the function", let's see how it does it

function foo() {
    var name = "Eva";
    function bar() {
        console.log(name);
    }

     

    return bar;}var result = foo();result();    // Eva

A function bar is defined in the foo function, and the variable name in foo is logged in console.log in bar, and bar is returned. The result is executed globally, and the value of name is printed, which means that what we cannot achieve above is Has the problem that the global scope cannot access the internal variables of the function been solved? ? That's right! ! !

why? Because usually after a function is executed, it will be recycled by the garbage collection mechanism, and its scope is also present, but in this example, when bar is returned, the scope of the foo function is saved as its parent scope. , And has not been recycled, so the scope of foo can still be accessed. This is why it leaks memory. If it is not manually released, it will always exist.

Let’s look at a few questions that we often encounter when doing questions.

for (var i = 0; i < 5; i++) {    setTimeout( function timer() {
        console.log(i);  
    }, 1000);}// 5 5 5 5 5

The result is five 5s, because all the i variables of the console statement are taken from the scope of the for loop, and after 1 second, the i of this scope is already 5, so 5 5s will be printed.

for (var i = 1; i <= 5; i++) {    (function(i){        setTimeout( function () {
              console.log(i);
          },  1000 );
    })(i);
 }
 // 1 2 3 4 5

In the above code, an immediate execution function is defined in the for sequence. This function is generally used to construct private variables to avoid global pollution. Each console statement has its own scope, and the current i is stored in the scope. Therefore, the execution of these console statements after 1000ms are all i obtained from their respective scopes.

Let's look at another example,

for (let i = 1; i <= 5; i++) {      setTimeout( function timer() {
               console.log(i);  
      }, 1000 );}// 1 2 3 4 5

This code uses let to define variables. We all know the block-level scope of the variables defined by let, and bind the i value to each iteration of the loop, that is, on each console statement, which is also a good solution. problem.

Summary: In "js advanced programming", a closure is defined as a function that has the right to access variables in the scope of another function. But I prefer another way of saying: functions that reference free variables. Defining a function in a function to access the parent function variable and return the function is just a way to achieve closure. What is returned is a closure, a function that carries the scope of a free variable



Nice
View more
  • x
  • convention:

Comment

You need to log in to comment to the post Login | Register
Comment

Notice: To protect the legitimate rights and interests of you, the community, and third parties, do not release content that may bring legal risks to all parties, including but are not limited to the following:
  • Politically sensitive content
  • Content concerning pornography, gambling, and drug abuse
  • Content that may disclose or infringe upon others ' commercial secrets, intellectual properties, including trade marks, copyrights, and patents, and personal privacy
Do not share your account and password with others. All operations performed using your account will be regarded as your own actions and all consequences arising therefrom will be borne by you. For details, see " User Agreement."

My Followers

Login and enjoy all the member benefits

Login

Block
Are you sure to block this user?
Users on your blacklist cannot comment on your post,cannot mention you, cannot send you private messages.
Reminder
Please bind your phone number to obtain invitation bonus.