Introduction to JavaScript Closures (Masaki) _javascript tips

Source: Internet
Author: User
Tags closure comparison table
Closures are very obscure--closures, which are paragraphs that have a syntax field in a particular region, and that have persistent references (read and write) to a Non-persistent variable value capability on an execution field that is outside the scope of the region itself. The non-persistent variables of these external execution fields magically retain their values (deep links) when the closures were initially defined (or created). In short, a closure is a variable in another scope that it obtains from the previous function or scope (key-value pairs), which are not destroyed with the execution of the upper-level function. Zhou said more clearly, the closure is the "property sheet", closures is a block of data, closures is a storage "name=value" of the comparison table. It's as simple as that. However, it must be emphasized that closures are a run-time concept.
In JavaScript, closures (Closure) have two features:
As a reference to a function variable-when the function returns, it is active.
A closure is when a function returns, a stack area that does not release resources.
Now the more agreeable closure implementation has the following three kinds
Copy Code code as follows:

With (obj) {
This is an object closure.
}

Copy Code code as follows:

(function () {
function closures
})()

Copy Code code as follows:

try{
//...
catch (e) {
Catch closure but not in IE.
}

A few useful examples
Copy Code code as follows:

Closed-Pack uniqueid*************
UniqueID = (function () {//The invocation object of this function holds the value
var id = 0; That's the value of the private eternity.
The outer function returns a nested function that has access to a constant value
That's the nested function we keep in the variable UniqueID.
return function () {return id++;}; return, self added.
})(); Call the outer function after the definition.
Document.writeln (UniqueID ()); 0
Document.writeln (UniqueID ()); 1
Document.writeln (UniqueID ()); 2
Document.writeln (UniqueID ()); 3
Document.writeln (UniqueID ()); 4

Copy Code code as follows:

Closed Bao Jie by *************
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 (a);

Copy Code code as follows:

function User (properties) {
Here you must declare a variable 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 for the
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 ());

Attached today in worry-free to see the problem:
Requirements:
Let the onclick events of these three nodes correctly eject the corresponding parameters.
Copy Code code 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 it's all back to 4.
}
}
</script>

<!doctype html> <title>javascript Closures by Masaki </title> <meta charset= "Utf-8"/> <meta name= "key Words "content=" javascript closures by Masaki "/> <meta name=" description "content=" JavaScript closures by Masaki "/> Type= "Text/javascript" > window.onload = function () {for (Var i=1 i < 4; i++) {var id = document.getElementById ("A "+ i); Id.onclick = function () {alert (i);//Now Returns 4}}} </script> <p>javascript closures by Masaki </p> <ul& Gt <li id= "A1" >aa</li> <li id= "A2" >aa</li> <li id= "A3" >aa</li> </ul>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

My explanation is that the onclick binding function function () {alert (i)} is scoped to the Li object, where alert's I is scoped to window, Each loop is rewriting the WINDOW.I value, so the loop is over, I is 4, and the LI element is 4.
Workaround:
Use function closures.
Copy Code code as follows:

var lists = document.getElementsByTagName ("Li");
for (Var i=0,l=lists.length i < L; i++) {
Lists[i].onclick = (function (i) {//Save in external function
return function () {
alert (i);
}
}) (i);
}

Copy Code code 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)
}
}
}

<!doctype html>-<title>javascript closures by Masaki </ title> <meta charset= "Utf-8"/> <meta name= "keywords" content= "javascript closures by Masaki"/> <meta name= "de Scription "content=" JavaScript closures by Masaki "/> <script type=" Text/javascript "> window.onload = function () {var l ists = document.getElementsByTagName ("Li"); for (Var i=0,l=lists.length i < L; i++) {Lists[i].onclick = function () {var t = i; return function () {alert (t+1)}} ()} </script> <p>javascript closure by Masaki (function closure) </p> <ul> <li id= "A1" >aa</li> <li id= "A2" >aa</li> <li id= "A3" >aa</li> </ul> </textar ea>
[ctrl+a all bets: If you need to introduce external JS need to refresh to perform]

Leveraging event Proxies
Copy Code code as follows:

var ul = document.getElementsByTagName ("ul") [0];
Ul.onclick = function () {
var e = Arguments[0] | | Window.event,
target = e.srcelement? E.srcelement:e.target;
if (target.nodeName.toLowerCase () = = "Li") {
Alert (Target.id.slice (-1))
}
}

<textarea id="runcode49702"><!doctype html> <title>javascript closures by Masaki </title> <meta charset= "Utf-8"/> <meta name = "keywords" content= "javascript closures by Masaki"/> <meta name= "description" content= "JavaScript closures by Masaki"/> Ript type= "Text/javascript" > window.onload = function () {var ul = document.getElementsByTagName ("ul") [0]; Ul.onclick = function () {var e = arguments[0] | | window.event, target = e.srcelement? e.srcelement:e.target; if (target.nodeName.toLowerCase () = = "Li") {alert (Target.id.slice ( -1)}}} </script> <p>javascript closure b Y Masaki (event agent) </p> <ul> <li id= "A1" >aa</li> <li id= "A2" >aa</li> <li id= "A3" >a A</li> </ul></textarea>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

Leave the temporary variable on the element node.
Copy Code code 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)
}
}

<!doctype html> <title>javascript Closures by Masaki </title> <meta charset= "Utf-8"/> <meta name= "key Words "content=" javascript closures by Masaki "/> <meta name=" description "content=" JavaScript closures by Masaki "/> Type= "Text/javascript" > window.onload = function () {var lists = document.getElementsByTagName ("Li"); For (var i=0,t=1,el el = lists[i++];) {el.i = t++ El.onclick = function () {alert (THIS.I)}}} </script> ; H1>javascript closures by Masaki (the properties of a temporary variable into an object) </p> <ul> <li id= "A1" >aa</li> <li id= "A2" > Aa</li> <li id= "A3" >aa</li> </ul>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

Object closures caused by using the WITH statement.
Copy Code code 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)};
}

<!doctype html> <title>javascript Closures by Masaki </title> <meta charset= "Utf-8"/> <meta name= "key Words "content=" javascript closures by Masaki "/> <meta name=" description "content=" JavaScript closures by Masaki "/> Type= "Text/javascript" > window.onload = function () {var els = document.getelementsbytagname ("Li") for (Var i=0,n=els. length;i<n;i++) {with ({i:i}) Els[i].onclick = function () {alert (i)}; } </script> <p>javascript Closures by Masaki (object closures) </p> <ul> <li id= "A1" >aa</li> <l I id= "A2" >aa</li> <li id= "A3" >aa</li> </ul>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

Exception closures constructed using the Try...catch statement:
Copy Code code 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)
}
}
}

<!doctype html> <title>javascript Closures by Masaki </title> <meta charset= "Utf-8"/> <meta name= "key Words "content=" javascript closures by Masaki "/> <meta name=" description "content=" JavaScript closures by Masaki "/> Type= "Text/javascript" > window.onload = function () {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)}}} </script> <p>javascript closure by Masaki (Exception closure) ;/h1> <ul> <li id= "A1" >aa</li> <li id= "A2" >aa</li> <li id= "A3" >aa</li> & Lt;/ul>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

Copy Code code as follows:

var els = document.getelementsbytagname ("Li");
(' +array (els.length+1)). Replace (/./g,function (a,i) {
Els[i].onclick=function () {alert (i)}
})
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.