JavaScript intermediate notes (4)

Source: Internet
Author: User
Another important knowledge in JavaScript-closures.

5. Closure


Closure means that the inner function can reference the variables in the function that enclose it, even if the execution of the outer function is terminated.
Let's look at a closure example first.

<Script type = "text/javascript">
Function add (num ){
Return function (toAdd ){
Return num + toAdd; // code ①
}
}

Var addFive = add (5); // addFive is function (toAdd) {return num + toAdd ;}
Var count = addFive (3); // at this time, count is num + toAdd
Alert (count); // 8
</Script>

Code ① Is in the inner layer of the function, but it can use the variable num of the outer layer.

Closing also solves another common Js problem and the impact of global variables.
By automatically executing the anonymous function combination closure, you can hide the original global variables. See the following example:

<Script type = "text/javascript">
(Function (){
Var msg = "Hello ";
Window. onunload = function (){
Alert (msg); // output Hello
}
})()

// Alert (msg); // undefined
</Script>

The closure is often used when setTimeout is used.

<Html>
<Head>
<Title> demo </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Script type = "text/javascript">
Window. onload = function (){
Var obj = document. getElementById ("abc ");
Obj. style. border = "1px solid #000 ";
SetTimeout (Function (){
Obj. style. color = "red ";
}, 1000)

Function DeAlert (msg, time ){
SetTimeout (Function (){
Alert (msg );
}, Time)
}
DeAlert ("hello", 2000 );
}
</Script>
</Head>
<Body>
<Div id = "abc"> CssRain </div>
</Body>
</Html>

Using setTimeout () in this way can avoid some problems.

Of course, using closures also causes some problems. The following code is used:

<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> demo </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Script type = "text/javascript">
Window. onload = function (){
Var ul = document. getElementById ("abc ");
Var li = document. getElementsByTagName ("li ");
For (var I = 0; I <li. length; I ++ ){
Li [I]. onclick = function (){
Alert ("the number you clicked is" + I + "li. ");
}
}
}
</Script>
</Head>
<Body>
<Ul id = "abc">
<Li> AAA </li>
<Li> BBB </li>
<Li> CCC </li>
</Ul>
</Body>
</Html>

Click the serial number 3 in the pop-up window of li. It is not the correct serial number. The referenced value is the last value assigned.
We can use the following code to solve the problem:

<Script type = "text/javascript">
Window. onload = function (){
Var ul = document. getElementById ("abc ");
Var li = document. getElementsByTagName ("li ");
For (var I = 0; I <li. length; I ++ ){
(Function () {// use a self-executed anonymous function to stimulate the scope
Var B = I; // remember the value in this scope
Li [B]. onclick = function () {// use the value just remembered, variable B
Alert ("the number you clicked is" + B + "li. ");
}
})()
}
}
</Script>

By using closures to control the scope, we can meet our requirements.
The above code can be divided:

<Script type = "text/javascript">
Window. onload = function (){
Var ul = document. getElementById ("abc ");
Var li = document. getElementsByTagName ("li ");
Function (){
Var B = 0;
Li [B]. onclick = function (){
Alert ("the number you clicked is" + B + "li. ");
}
}
Function B (){
Var B = 1;
Li [B]. onclick = function (){
Alert ("the number you clicked is" + B + "li. ");
}
}
Function c (){
Var B = 2;
Li [B]. onclick = function (){
Alert ("the number you clicked is" + B + "li. ");
}
}
A ();
B ();
C ();
}
</Script>

The concept of closure is not easy to grasp. I also spent a lot of time and effort to understand it.

6. Summary
Notes (2), (3), and (4) explain several important content in JavaScript, including references, function overloading, scopes, context objects, and closures.

Key content of a reference: pointer, array reference, string reference, difference, value passing, and address passing.
Key Content of function overloading: number of parameters, parameter type, arguments, pseudo array, typeof, constructor, difference-string and object.
Key Content of the scope: function division, global scope, global object, window object attributes, local scope, explicit declaration, and implicit declaration.
Key Content of the context object: this variable, call, apply, parameter difference, array.
The key content of the closure is: inner function, outer function, variable, setTimeout, closure problem, last assignment, closure and scope.

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.