Application of JavaScript closures

Source: Internet
Author: User

My impression is that JavaScript's closures are in the advanced category and are nothing more than a load of force in an interview. You see a young man around me, one day I pretend to ask him what is the JavaScript of the closure, he actually even heard. But he made the front-end thing come quickly, just like the other lads I had seen.

This shows that it does not seem to matter whether the closure is known or not.

However, these days to write some front-end code, I think you should understand this thing.

The so-called closure, as I understand it, is a JavaScript function (the parent function) has a child function, and the outside world can use this sub-function to access the variables inside the parent function. The purpose of closures is to protect the variables in these parent functions so that they survive the end of the parent function and are not recycled by the JavaScript garbage collection mechanism.

How do you understand it? An example is described.

For example, we output a bunch of list items on a page, each with an onclick event:

<ul><li id="li1" onclick="hi(1)">我是1</li><li id="li2" onclick="hi(2)">我是2</li>...</ul>

We will find that there are many duplicate codes in the list items, resulting in a lot of page code. If we do not advance to each

  • Setting events, instead of binding the OnClick event to the page after it has been loaded, makes the page much simpler and reduces bandwidth consumption.
  • So, how do you bind events? If we write like this:

    function hi(number){    alert("我是 "" !");}$(function(){    for(var1100; i++){        $("#li" + i).bind("click",function(){            hi(i);        });    }});

    So eventually, clicking on each list item will show "I'm 100!". The reason is that after the loop is over, I is 100.

    If you change to this:

    function hi(number){    returnfunction(){//子函数,闭包机制将传入的number存储起来        alert("我是 "" !");    };}$(function(){    for(var1100; i++){        $("#li" + i).bind("click",hi(i));    }});

    Then we can get the result we want. The reason is that, in the function hi (number), the closure is set up, and when the event is bound, it is stored.

    To understand the above statement, it is necessary to do some clarification about the event binding here:

    $("#li" + i).bind("click",函数定义);

    This means that the function definition is the one that binds to the element event, not a function to run the statement! It must be clear. For example, function Hi (Numbert) {...} is a function definition, hi (i) is a function run statement.

    Let's take a look at the code by slightly modifying it:

     function hi(number){//function body is a normal execution statementAlert"I was impatient."+ number +" !");} function hi_bb(number){//Function body Returns a child function instance    return  function(){//Sub-functions, closuresAlert"I Am"+ number +" !"); };} $( function(){     for(vari =1; I <3; i++) {//At this time hi execution, pop-up information, bind failed$("#li"+ i). Bind ("click", hi (i));//At this time HI_BB executes, returns a function definition, the binding succeeds$("#li"+ i). Bind ("click", HI_BB (i)); }});

    At the time of event binding, the function hi and HI_BB are executed. Hi inside is the normal execution of the statement, Hula啦, the list item fails to bind the event, and after HI_BB executes, the function definition is returned, so the list item event binding succeeds.

    Let's review the role of closures: protect the variables in the parent function so that the variables continue to survive after the parent function runs, and are not recycled by the JavaScript garbage collection mechanism. in this example, when the event is bound, HI_BB executes, and I is passed in as a parameter. Originally the Loop statement, page onload function end, I should not exist. But because there are closures in the HI_BB, each of the values of I is preserved, in the subsequent click events, play a role.

    These words seem to be reluctant and loaded, I am also in the experience. If it is an object-oriented language, it is well understood that objects are constructed from the same class, and the values of the properties and variables in the object are different. JavaScript is not object-oriented, there are no classes, only functions. Maybe a closure is one of its object-oriented simulations. That's what I'm thinking.

    I have also summed up the closure, and now wrote an article, feeling and deepened a little understanding:
    http://blog.csdn.net/leftfist/article/details/41868659

    You can run the code on the website http://jsfiddle.net/to verify and control.

    Copyright NOTICE: This article for Bo Main original 屙 article, like you take away.

    Application of JavaScript closures

    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.