The definition of closure is very obscure - a closure refers to a paragraph whose syntactic domain is located in a specific area and has the ability to continuously refer to (read and write) non-persistent variable values in the execution domain outside its own scope within the area. . These non-persistent variables outside the execution scope magically retain their values (deep links) when the closure was originally defined (or created). Simply put, a closure stores a copy of the variables (key-value pairs) it obtains from the upper-level function or scope in another scope, and these key-value pairs will not follow the execution of the upper-level function. Destroyed upon completion. Zhou Aimin said more clearly that closure is an "attribute table", closure is a data block, and closure is a comparison table that stores "Name=Value". It's that simple. However, it must be emphasized that closure is a runtime concept.
Closure in Javascript has two characteristics:
As a reference to a function variable - it is activated when the function returns.
A closure is a stack area that does not release resources when a function returns.
There are currently three recognized closure implementations:
with(obj){
//Here is the object closure
}
(function(){
//Function closure
})()
try{
//...
} catch(e) {
//catch closure but not in IE
}
A few useful examples
//**************** closure uniqueID****************
uniqueID = (function(){ //The calling object of this function saves the value
var id = 0; //This is the private persistent value
//The outer function returns a persistent value that has access to it The nested function
//That is the nested function we save in the variable uniqueID.
return function(){return id;}; //Return, self-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
//******************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(a);
function User( properties ) {
//A variable must be declared here to point to the current instance
var objthis = this;
for ( var i in properties ) {
(function(){
//Inside the closure, t is new every time, and the value of properties[i] is inside for
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 is the question I saw on Wuyou today:
Request:
Let this The Onclick events of the three nodes can correctly pop up the corresponding parameters.
]
My explanation is, onclick The scope of the binding function function(){alert(i)} is the corresponding li object, and the scope of i in alert is window. Each loop is rewriting the value of window.i, so after the loop is completed, i is already 4, whichever li element is clicked is 4.
Solution:
Use function closures.
The 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 in external function
return function(){
alert(i);
}
})(i);
}
The 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)
}
}
}
If you need to introduce external Js, you need to refresh to execute
]
Use event proxy
Copy code
The 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.target;
if(target .nodeName.toLowerCase() == "li"){
alert(target.id.slice(-1))
}
}
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
Keep temporary variables in the element on the node. Copy code
The 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)
}
}
使用with语句造成的对象闭包。
var els = document.getElementsByTagName("li")
for(var i=0,n=els.length;iwith ({i:i})
els[i].onclick = function() { alert(this.innerHTML+i) };
}
使用try...catch语句构造的异常闭包:
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)
}
}
}
var els = document.getElementsByTagName("li");
(''+Array(els.length+1)).replace(/./g,function(a,i){
els[i].onclick=function(){alert(i)}
})