Introduction to the closure of javascript (situ zhengmei)

Source: Internet
Author: User
Tags comparison table

The definition of a closure is very obscure-a closure refers to a syntax domain located in a specific area with a continuous reference (read/write) section of the non-persistent variable value capability in the execution domain outside the region itself. The non-persistent variables of these external execution domains magically keep their values (deep links) when they are initially defined (or created) in the closure ). To put it simply, the closure stores a copy of the variable (key-Value Pair) it acquires from the upper-level function or scope in another scope ), however, these key-value pairs will not be destroyed as the upper-level functions are executed. Zhou aimin makes it clearer that a closure is an "Attribute Table", a closure is a data block, and a closure is a comparison table containing "Name = Value. That's simple. However, it must be emphasized that closures are a concept of runtime.
Closure in Javascript has two features:
As a reference to a function variable-when a function is returned, it is activated.
A closure is a stack that does not release resources when a function returns.
There are three types of closure implementations that are currently quite accepted: Copy codeThe Code is as follows: with (obj ){
// Here is the object Closure
}

Copy codeThe Code is as follows: (function (){
// Function Closure
})()

Copy codeThe Code is as follows: try {
//...
} Catch (e ){
// Catch closure, but not in IE
}

Several useful examplesCopy codeThe Code is as follows: // ************* closure uniqueID *************
UniqueID = (function () {// Save the value of the called object of this function
Var id = 0; // This is the private permanent value
// The outer function returns a nested function with the right to access the permanent value.
// That is the nested function stored in the variable uniqueID.
Return function () {return id ++;}; // return, auto-increment.
}) (); // Call the outer function after definition.
Document. writeln (uniqueID (); // 0
Document. writeln (uniqueID (); // 1
Document. writeln (uniqueID (); // 2
Document. writeln (uniqueID (); // 3
Document. writeln (uniqueID (); // 4

Copy codeThe Code is as follows: // ************** closure factorial *************
Var a = (function (n ){
If (n <1) {alert ("invalid arguments"); return 0 ;}
If (n = 1) {return 1 ;}
Else {return n * arguments. callee (n-1 );}
}) (4 );
Document. writeln ();

Copy codeThe Code is as follows: function User (properties ){
// A variable must be declared to point to the current instance.
Var objthis = this;
For (var I in properties ){
(Function (){
// In the closure, t is new every time, and the value of properties [I] is in
Var t = properties [I];
Objthis ["get" + I] = function () {return t ;};
Objthis ["set" + I] = function (val) {t = val ;};
})();
}
}
// Test code
Var user = new User ({
Name: "Bob ",
Age: 44
});
Alert (user. getname ());
Alert (user. getage ());
User. setname ("Mike ");
Alert (user. getname ());
Alert (user. getage ());
User. setage (22 );
Alert (user. getname ());
Alert (user. getage ());

The following are the questions you can see today:
Requirements:
Make the Onclick events of the three nodes correctly pop up corresponding parameters.Copy codeThe Code is as follows: <ul>
<Li id = "a1"> aa </li>
<Li id = "a2"> aa </li>
<Li id = "a3"> aa </li>
</Ul>
<Script type = "text/javascript">
For (var I = 1; I <4; I ++ ){
Var id = document. getElementById ("a" + I );
Id. onclick = function (){
Alert (I); // now all returns 4
}
}
</Script>

<Meta charset = "UTF-8"> <meta name = "keywords" content = "javascript closure by situ zhengmei"> <meta name = "description" content = "javascript closure by situ zhengmei "> <br/> javascript closure by situ zhengmei <ul> <li id =" a1 "> aa </li> <li id =" a2 "> aa </li> <li id = "a3"> aa </li> </ul> <p>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

In my explanation, The onclick binding function () {alert (I)} has the corresponding li object, and the scope of alert I in it is window, every loop is rewriting window. the value of I. Therefore, after the loop is complete, I is 4, and the clicked li element is 4.
Solution:
Use the function closure.Copy codeThe Code is as follows: var lists = document. getElementsByTagName ("li ");
For (var I = 0, l = lists. length; I <l; I ++ ){
Lists [I]. onclick = (function (I) {// save it to an external function
Return function (){
Alert (I );
}
}) (I );
}

Copy codeThe Code is as follows: var lists = document. getElementsByTagName ("li ");
For (var I = 0, l = lists. length; I <l; I ++ ){
Lists [I]. onclick = new function (){
Var t = I;
Return function (){
Alert (t + 1)
}
}
}

<Meta charset = "UTF-8"> <meta name = "keywords" content = "javascript closure by situ zhengmei"> <meta name = "description" content = "javascript closure by situ zhengmei "> <br/> javascript closure by situ zhengmei (function closure) <ul> <li id = "a1"> aa </li> <li id = "a2"> aa </li> <li id = "a3"> aa </ li> </ul> <p>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

Use event proxyCopy codeThe Code is as follows: var ul = document. getElementsByTagName ("ul") [0];
Ul. onclick = function (){
Var e = arguments [0] | window. event,
Target = e. srcElement? E. srcElement: e.tar get;
If (target. nodeName. toLowerCase () = "li "){
Alert (target. id. slice (-1 ))
}
}

<Meta charset = "UTF-8"> <meta name = "keywords" content = "javascript closure by situ zhengmei"> <meta name = "description" content = "javascript closure by situ zhengmei "> <br/> javascript closure by situ zhengmei (event proxy) <ul> <li id = "a1"> aa </li> <li id = "a2"> aa </li> <li id = "a3"> aa </ li> </ul> <p>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

Save the temporary variables on the element node.Copy codeThe Code is as follows: var lists = document. getElementsByTagName ("li ");
For (var I = 0, t = 0, el; el = list [I ++];) {
El. I = t ++
El. onclick = function (){
Alert (this. I)
}
}

<Meta charset = "UTF-8"> <meta name = "keywords" content = "javascript closure by situ zhengmei"> <meta name = "description" content = "javascript closure by situ zhengmei "> <br/> javascript closure by situ zhengmei (converting temporary variables into attributes of an object) <ul> <li id = "a1"> aa </li> <li id = "a2"> aa </li> <li id = "a3"> aa </ li> </ul> <p>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

Object closure caused by the with statement.Copy codeThe Code is as follows: var els = document. getElementsByTagName ("li ")
For (var I = 0, n = els. length; I <n; I ++ ){
With ({I: I })
Els [I]. onclick = function () {alert (this. innerHTML + I )};
}

<Meta charset = "UTF-8"> <meta name = "keywords" content = "javascript closure by situ zhengmei"> <meta name = "description" content = "javascript closure by situ zhengmei "> <br/> javascript closure by situ zhengmei (Object closure) <ul> <li id = "a1"> aa </li> <li id = "a2"> aa </li> <li id = "a3"> aa </ li> </ul> <p>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

Exception closure constructed using try... catch statement:Copy codeThe Code is as follows: var lists = document. getElementsByTagName ("li ");
For (var I = 0, l = lists. length; I <l; I ++ ){
Try {
Throw I;
} Catch (I ){
Lists [I]. onclick = function (){
Alert (I)
}
}
}

<Meta charset = "UTF-8"> <meta name = "keywords" content = "javascript closure by situ zhengmei"> <meta name = "description" content = "javascript closure by situ zhengmei "> <br/> javascript closure by situ zhengmei (Abnormal closure) <ul> <li id = "a1"> aa </li> <li id = "a2"> aa </li> <li id = "a3"> aa </ li> </ul> <p>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

Copy codeThe Code is as follows: var els = document. getElementsByTagName ("li ");
(''+ Array (els. length + 1). replace (/./g, function (a, I ){
Els [I]. onclick = function () {alert (I )}
})

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.