JavaScript Closure Details _ basic knowledge

Source: Internet
Author: User
Tags closure function definition

In the previous article, we gave an overview of the preliminary explanation, before writing this blog to write a few classic cases, given that those cases are more comprehensive, and gradually have this blog, so for learning and in-depth JavaScript is also easier to start.

Order

A colleague to interview, the interviewer asked a question: You write a closure I see? So colleagues rushed to write the following code:

Copy Code code as follows:

function fn () {
Alert (' Hello JavaScript Closure!!! '); /Mom eggs, E is not good, to find an interpreter to the closure of the word written out
}
FN ();

Then the interviewer shook his head and said, "How can you call it a closure?" In the end, the two of them will not fight, the colleague decisively leave, interviewer what thing? (This story is pure fiction, if the similarities are pure coincidence)

Closures may be in the eyes of many people are "big bad" technology, may be in the eyes of many people is the closure of the package:

Example 1:

Copy Code code as follows:

function fn () {
return function () {
Alert (' Example 1 ');
}
}
fn () ();

Example 1 PS: This looks not very advanced, it looks like this person's level is not very well!

Example 2:

Copy Code code as follows:

;(function () {
Alert (' Example 2 ');
})();

Example 2 PS: This looks higher than the previous one, plus a semicolon before the first parenthesis, why add a semicolon, OK, let's leave this question here for later.

Example 3:

Copy Code code as follows:

~FUNCTION fn () {
Alert (' Example 3 ')
}();

Example 3 PS: This is the highest level, simply hanging fried days, I read less, you don't lie to me!

The main reading is not much, only can write these three kinds of "closure", I believe Bo friends can write more excellent "closure"; Please pause my nonsense, then study the function of the operation of the mechanism, looks like someone already know, certainly is the scope, I really do not want to add this scope in the title, so always feel almost meaning, This is a couple of things that are meant to be together, why should we repeat them? Old habits, first on the code:

Copy Code code as follows:

var n = 10;
function fn () {
alert (n);
var n = 9;
alert (n);
}
FN ();

To put it simply, we draw (the owner will only use Windows with its own drawing software, if you have better to ask Bo friends recommended) to analyze:

Analysis 1

From the diagram we see two scopes, one is window scope (top-level scope), one is a private scope formed when FN calls; what is a scope, the scope is actually the environment of code execution. A chestnut, a student his learning environment is the school, the equivalent of his scope is the school, if this student is very naughty, the evening often fanqiang to play games, equivalent to the formation of a private environment, the scope is Internet cafes. All right! This chestnut is too TM like the master himself, not by exclamation: "An idle youth, grow up and kick." Or back to the point, in fact, the definition of the function fn is a description of a piece of code (red box in the figure), when this FN call (the green box in the diagram), it will form a scope, of course, the scope of the code before the execution will also be explained, I will not tell you that the scope is when it is finished and will be destroyed, This FN invocation also forms a new scope, then executes the pre-interpretation, then executes the code, and finally executes the destroy.

Understanding closures

We know that a function is invoked to form a private scope (execution environment) when executed, and this private scope is the closure. Looking back at the closure or the legendary "Big Bad"? Let's take a look at the first interview story and the three examples I've written, which are actually closures, and exactly the three examples are common forms of closures.

Application Scenarios

Now there is such a demand: HTML page has a UL tag, ul below 5 Li tags, ask to click an arbitrary Li, pop-up clicked on the index of this Li (index from the beginning of the 0) location, HTML structure is as follows:

Copy Code code as follows:

<ul id= "ul" >
<li> List 1</li>
<li> List 2</li>
<li> List 3</li>
<li> List 4</li>
<li> List 5</li>
</ul>

Witty I rushed to write the following code:

Copy Code code as follows:

var lis = document.getElementById (' ul '). getElementsByTagName (' Li ');
for (var i = 0, len = lis.length i < len; i++) {
Lis[i].onclick = function () {
alert (i);
};
}

Final Test to see if it is perfect to achieve this requirement:

Found that no matter how many clicks, the end of the final pop-up this result, and the demand expected results: Click on Listing 1 pop-up 0, click List 2 pop-up 1, click List 3 pop-up 2 ... At this moment just want to use this picture to describe the mood now:

(When the prototype does not work as designed when it is demonstrated)

How can this be good, why always pop 5? The theory is very correct! We might as well draw to analyze the following:

In fact, we just give each of the Li's onclick is actually saved a section of the function of the description string, this string is the content of the red box above, if you still do not believe that I have a picture of the truth:

Under the Chrome console, enter: Lis[4].onclick, whose value is the description of the function. When we clicked on the 5th list, it was the equivalent of Lis[4].onclick (), which called the function description, and we knew that the function would form a private scope when it was invoked, and that the private scope would be interpreted first and then the code was executed, and then I would find There is no I in the current private scope, then I was found under the window scope, so every click POPs up 5.

Obviously the above code does not meet this requirement, we write the code is not correct, we think about the cause of the problem? The reason is that every time the click is read under Window I, at this time the value of this I is already 5, and then have the following code:

Mode one:

Copy Code code as follows:

var lis = document.getElementById (' ul '). getElementsByTagName (' Li ');
function fn (i) {
return function () {
alert (i);
}
}
for (var i = 0, len = lis.length i < len; i++) {
Lis[i].onclick = fn (i);
}

Mode two:

Copy Code code as follows:

var lis = document.getElementById (' ul '). getElementsByTagName (' Li ');

for (var i = 0, len = lis.length i < len; i++) {
;(function (i) {
Lis[i].onclick = function () {
alert (i);
};
}) (i);
}

Mode three:

Copy Code code as follows:

var lis = document.getElementById (' ul '). getElementsByTagName (' Li ');

for (var i = 0, len = lis.length i < len; i++) {
Lis[i].onclick = function fn (i) {
return function () {
alert (i);
}
} (i);
}

Three ways to write in one breath, the idea is the same, that is, this variable i with a private variable stored, here I will only speak mode two, of course, understand that one of the rest is understood. By convention, we draw a step-by-step analysis:

I have described the entire code execution in detail, and it should be noted that each Li's onclick attribute is occupied (function (i) {...}) (i) scope, which is not destroyed after the function has been executed, because it is occupied by the outside Li (this Li is under Window scope), so this scope is not destroyed. function () {alert (i) when clicking on any one of the Li; will be executed and form a scope that does not have I, it will go (function () {...}) (i) The scope of I, finally in the formal parameter to find I, this parameter i is the value of the for loop newsletters in; This example cleverly uses closures to store values and solves the problem perfectly.

PS: Just said (function (i) {...}) (i) A semicolon is preceded by the reason for preventing the preceding statement from forgetting to add a semicolon, which causes JavaScript to parse with an error, and that is it. Of course, one of the above scenarios is the tabs implementation principle, there can be other implementations, such as custom attribute mode, through the DOM node relationship to find the index, and the main use of this method is to deepen the understanding of the closure.

Summarize

Closures are not legendary tall, the core of which is to understand function definition, invocation, function call will form a new private scope, when a scope is outside Occupy, then this scope will not be destroyed. The students read very little, there are wrong places to ask Bo friends correct, but also thank you for the main article of the support.

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.