JavaScript closures _ basic knowledge-js tutorial

Source: Internet
Author: User
This article introduces the javascript closure in detail, which is very detailed. We recommend it to anyone who needs it. In the previous article, we gave an overview of the pre-interpretation. before writing this blog post, we plan to write several typical cases. Considering that these cases are comprehensive, we will gradually get this blog post, this makes it easier to learn and explore JavaScript.

Collation

When a colleague went to the interview, the interviewer asked: Do you want to write a closure? As a result, my colleagues wrote the following code:

The Code is as follows:


Function fn (){
Alert ('Hello JavaScript Closure !!! '); // Mom, E text is not good, and closure words are written only after translation.
}
Fn ();

Then the interviewer shook his head and said, "How can this be called a closure ?", In the end, the two won't be able to argue, and their colleagues leave decisively. What is the interviewer doing? (This story is purely fictitious. If there are similarities, it is a coincidence)

Closures may be "Too Tall or difficult" in the eyes of many people, and they may be regarded as closures only in this way:

Example 1:

The Code is as follows:


Function fn (){
Return function (){
Alert ('example 1 ');
}
}
Fn ()();

Example 1 PS: This looks not very advanced, it looks like this person is not very good!

Example 2:

The Code is as follows:


; (Function (){
Alert ('example 2 ');
})();

Example 2 PS: This looks more advanced than the previous one, and a semicolon is added before the first bracket. Why should we add a semicolon? Well, let's leave this question here first, I will talk about it later.

Example 3:

The Code is as follows:


~ Function fn (){
Alert ('example 3 ')
}();

Example 3 PS: This is the highest level. It's just like a sky. I have a few books. Don't lie to me!

I believe that bloggers can write more and more excellent "closures" because I have not studied much about the three types of "closures". Now, please pause my preparation, next, I will study the function running mechanism. It seems that someone already knows it. It must be a scope. I really don't want to add this scope to the title, so it's almost interesting, these items are all together. Why should they be repeated? Old habits, first go to the Code:

The Code is as follows:


Var n = 10;
Function fn (){
Alert (n );
Var n = 9;
Alert (n );
}
Fn ();

To put it simply, let's draw a picture (the ghost master will only use the drawing software that comes with Windows. If there is a better picture, we recommend it to you:

Analysis 1

We can see two scopes: window scope (top-level scope), and fn private scope formed when calling; what is scope and scope is actually the code execution environment. For example, a student's learning environment is a school, which is equivalent to a school. If this student is very naughty, FanQiang often plays games in Internet cafes at night, which forms a private environment, this scope is Internet cafes. Okay! This Chestnut is too TM like the Lord himself, so I can't help but sigh: "You don't have to work hard, grow up and fight ". Back to the question. In fact, the function fn is defined to point to the description of a piece of code (the red box in the figure). When this fn call (the Green Box in the figure), a scope is formed, of course, the code in this scope will be pre-interpreted before it is executed. I will not tell you that this scope will be destroyed after it is executed, and the re-call of this fn will form a new scope, then pre-explain the execution, execute the code, and destroy the execution.

Understanding closures

We know that a private scope (Execution Environment) is formed when a function is called and executed. This private scope is the closure. Let's look back at the closure, or is it the legendary "Too Tall? Let's look back at the first interview story and the three examples I wrote. They are actually closures. Specifically, the three examples are common forms of closures.

Application scenarios

There is a need: There is a ul tag in the HTML page, and there are five li tags under ul, You need to click any one li, the index of the clicked li (index starts from 0) is displayed. The HTML structure is as follows:

The Code is as follows:



  • List 1

  • List 2

  • List 3

  • List 4

  • List 5



I quickly wrote the following code:

The Code is as follows:


Var lis = document. getElementById ('ul '). getElementsByTagName ('lil ');
For (var I = 0, len = lis. length; I <len; I ++ ){
Lis [I]. onclick = function (){
Alert (I );
};
}

The final test is to see if it meets this requirement perfectly:

This result is displayed no matter how many clicks are made. The expected result is: Click List 1 to bring up 0, click List 2 to bring up 1, and click list 3 to bring up 2 ...... At this moment, I just want to use this picture to describe my current mood:

(When the prototype fails to run as designed)

How can this be done? Why is 5 always displayed? Theoretically correct! Let's draw a picture to analyze it:

In fact, we only give each li onclick a description string of the saved function, and the content of this string is in the red box. If you still don't believe it, I have a picture showing the truth:

Enter lis [4]. onclick in the Chrome console. The value is the description of the function. When we click the 5th list, it is actually equivalent to lis [4]. onclick () calls the description of this function. We know that the function will form a private scope when it is called for execution. In this private scope, it is also pre-interpreted and then executed by code, at this time, I will be searched, no I in the current private scope, and I will be found under the window scope, so 5 will pop up each click.

Obviously, the above Code cannot meet this requirement. Therefore, we cannot write the code correctly. What are the causes of the problem? The reason is that the I in the window is read every time you click it. At this time, the I value is already 5, so the following code is available:

Method 1:

The Code is as follows:


Var lis = document. getElementById ('ul '). getElementsByTagName ('lil ');
Function fn (I ){
Return function (){
Alert (I );
}
}
For (var I = 0, len = lis. length; I <len; I ++ ){
Lis [I]. onclick = fn (I );
}

Method 2:

The Code is as follows:


Var lis = document. getElementById ('ul '). getElementsByTagName ('lil ');

For (var I = 0, len = lis. length; I <len; I ++ ){
; (Function (I ){
Lis [I]. onclick = function (){
Alert (I );
};
}) (I );
}

Method 3:

The Code is as follows:


Var lis = document. getElementById ('ul '). getElementsByTagName ('lil ');

For (var I = 0, len = lis. length; I <len; I ++ ){
Lis [I]. onclick = function fn (I ){
Return function (){
Alert (I );
}
} (I );
}

I wrote three methods in one breath, and the thought is the same. I used a private variable to store the variable I. Here I only talk about method 2, of course, the rest of them will be clear. According to the Convention, we draw a picture to analyze it step by step:

I have described the execution of the entire code in detail. Note that the onclick attribute of each li is occupied (function (I ){... }) (I) scope, this function will not be destroyed after execution, because it is occupied by the outside li (this li is in the window scope, therefore, this scope will not be destroyed. When you click any li, function () {alert (I) ;}will be executed and a scope will be formed. This scope does not have I, and it will go to (function () {... }) (I) searches for I in the scope, and finally finds I in the form parameter. The value of this form parameter is passed in during the for loop. In this example, the closure is cleverly used to store the value, perfect solution.

PS: Just now (function (I ){... }) (I) Why should I add a semicolon to the front? The reason is to prevent the previous statement from forgetting the plus sign, which leads to an error in JavaScript parsing. That's all. Of course, one of the above application scenarios is the Tabs implementation principle. There can be other implementation methods, such as customizing attributes and finding indexes through DOM node relationships, the observer master adopts this method only to deepen the understanding of the closure.

Summary

Closure is not a legend. Its core is to understand the definition and call of a function. A new private scope will be formed during function calling. When a certain scope is occupied by the outside, this scope will not be destroyed. The primary school has very few books. If something is wrong, ask the bloggers to correct them and thank you for your support for the primary article.

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.