Closure-large front-end

Source: Internet
Author: User
Introduction when I first learned the word "closure", I was always overwhelmed. When I asked this question during the interview, it was also a vague answer. I always felt a layer of separation, I think this concept is amazing. If you can grasp it, you will surely make a great deal of effort. Actually, the closure is not so mysterious, it is everywhere .... Introduction

When I first learned the word closure at the front end, I was always overwhelmed. When I asked this question during the interview, it was also a vague answer. I always felt a layer of separation, I think this concept is amazing. If you can grasp it, you will surely make a great deal of effort. In fact, closures are not so mysterious and they are everywhere.

A short question

First, let's look at a problem.

Describe what is a closure in one sentence and write code to describe it.

If you can give an explanation without hesitation, the following text is not necessary for you to look down.
In this case, based on the materials and experience I have consulted, I would like to give a brief description here. If there is anything wrong, please correct me.

Answer the above question first, what is a closure.

A closure is a concept that describes the phenomenon of memory resident after the function is executed.

Code Description:

function foo() {    var a = 2;    function bar(){        console.log(a);    }    return bar;}var test = foo();test(); //2

The above Code clearly shows the closure.

The Lexical scope of function bar () can access the internal scope of foo. Then we pass the bar () function as a value type. In the above example, we use the function object referenced by bar () as the return value.

After foo () is executed, its internal scope is not destroyed, because bar () still maintains reference to the internal scope, thanks to the location of bar, it has a closure that covers the internal scope of foo (), so that the scope can survive for reference by bar () at any time later. This reference is actually a closure.
This is also the reason. When test is actually called, it can access the lexical scope at the time of definition, so it can access.

Function transmission can also be indirect:

Var fn; function foo () {var a = 2; function baz () {console. log (a) ;}fn = baz; // assign baz to the global variable} function bar () {fn () ;}foo (); bar (); // 2

Therefore, no matter what means the internal function is passed out of its lexical scope, it will hold a reference to the original definition scope. That is to say, the closure is used no matter where the function is executed. This is also the reason, so that we can easily use the callback function without worrying about its details.

In fact, when a callback function is used in a timer, event listener, ajax request, cross-window communication, Web Workers, or any other synchronous or asynchronous task, the closure is actually used.

Here, you may have a rough understanding of closures. I will give you a few examples to help you better understand closures.

Several more examples

First, let's take a look at the so-called immediate function execution.

var a = 2;(function IIFE() {    console.log(a);  })();//2

This immediate execution function is generally considered a classic closure example, which can work normally, but strictly speaking, it is not a closure.
Why?

Because this IIFE function is not executed outside its lexical scope. It is executed in the scope of the definition. In addition, variable a is searched through common lexical scopes, rather than through closures.

Another example is loop.

    

  • some text1
  • some text2
  • some text3
  • var handler = function(nodes) {    for(var i = 0, l = nodes.length; i < l ; i++) {                nodes[i].onclick = function(){            console.log(i);        }    }}var tabs = document.querySelectorAll('.tabs .tab');    handler(tabs);

    The expected results are log 0, 1, 2;

    The result after execution is three;

    Why?

    First, explain how this 3 came from,

    Let's take a look at the loop body. The ending condition of the loop is I <l, and the value of I is 3 when the first condition is set.
    Therefore, the output displays the final value of I at the end of the loop. According to the working principle of the scope, although the functions in the loop are defined separately in each iteration, they are all enclosed in a shared global scope, so there is actually only one I.

    The handler function is intended to pass the unique I to the event processor, but fails.
    Because the event processor function is bound to the I itself, rather than the I value of the function during construction.

    After knowing this, we can make corresponding adjustments:

    var handler = function(nodes) {    var helper = function(i){        return function(e){            console.log(i); // 0 1 2        }    }    for(var i = 0, l = nodes.length; i < l ; i++) {                nodes[i].onclick = helper(i);    }}

    Create an auxiliary function outside the loop so that the auxiliary function returns a function bound with the current I value, so that it will not be confused.

    After understanding this, we will find that the above processing is to create a new scope. In other words, each iteration requires a block scope.

    When it comes to block scope, you have to mention a word, that is, let.

    Therefore, if you do not want to use too many closures, you can use let:

    var handler = function(nodes) {    for(let i = 0, l = nodes.length; i < l ; i++) {                //nodes[i].index = i;        nodes[i].onclick = function(){            console.log(i); // 0 1 2        }    }}
    Closure in jQuery

    Let's look at an example.

         var sel = $("#con");      setTimeout( function (){          sel.css({background:"gray"});      }, 2000);

    The above Code uses the jQuery selector to find the element with the id of con and register the timer. After two seconds, set the background color to Gray.

    The magic of this code snippet is that after the setTimeout function is called, con is still kept inside the function. After two seconds, the background color of the p element whose id is con is indeed changed. It should be noted that setTimeout has been returned after the call, but con is not released because con references the global scope variable con.

    The above example helps us understand

    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.