JavaScript 闭包深入浅出
//1,闭包
1 $(document).ready(function(){ 2 var spans=$("#divTest span"); 3 for(var i=0;i<spans.length;i++){ 4 spans[i].onclick=function(){ 5 alert(i); 6 } 7 } 8 }); 9 $(document).ready(function(){ 10 var spans2=$("#divTest2 span"); 11 var spans=$("#divTest span"); 12 for(var i=0;i<spans2.length;i++){ 13 (function(num){ 14 spans2[i].onclick=function(){ 15 alert(num); 16 } 17 })(i); 18 spans[i].onclick=function(){ 19 alert(i); 20 } 21 } 22 });
//2,内部函数 ,在outerFn作用域内调用innerFn是有效的,而在outFn外部调用innerFn则是无效的。
1 function outerFn () { 2 document.write("Outer function</br>"); 3 function innerFn(){ 4 document.write("Inner function</br>"); 5 } 6 innerFn(); 7 } 8 outerFn();
//3,
1 var globalVar; 2 function outerFn () { 3 document.write("Outer function</br>"); 4 function innerFn(){ 5 document.write("Inner function</br>"); 6 } 7 globalVar=innerFn; 8 } 9 outerFn(); 10 globalVar();
//返回值的方式
1 function outerFn(){ 2 document.write("Outer function</br>"); 3 function innerFn(){ 4 document.write("Inner function</br>"); 5 } 6 return innerFn; 7 } 8 var fnRef=outerFn(); 9 fnRef();
//只要存在调用内部函数的肯能,JavaScript就会保留呗引用的函数。而且Javascript运行时需要跟踪引用这个内部函数的所有变量,知道最后一个变量废弃,JavaScript的垃圾收集器才能释放相应的内存空间。闭包是指:有权限访问另一个函数作用域的变量的函数。
// 4,变量作用域
1 function outerFn(){ 2 document.write("Outer function</br>"); 3 function innerFn(){ 4 var innerVar=0; 5 innerVar++; 6 document.write("Inner function\t"); 7 document.write("innerVar = "+innerVar+"</br>"); 8 } 9 return innerFn; 10 } 11 var fnRef=outerFn(); 12 fnRef(); 13 fnRef(); 14 var fnRef2=outerFn(); 15 fnRef2(); 16 fnRef2();
var globalVar=0; function outerFn(){ document.write("Outer function</br>"); function innerFn(){ globalVar++; document.write("Inner function\t"); document.write("globalVar = "+ globalVar +"</br/>"); } return innerFn; } var fnRef=outerFn(); fnRef(); fnRef(); var fnRef2=outerFn(); fnRef2(); fnRef2();
1 function outerFn(){ 2 var outerVar=0; 3 document.write("Outer function<br/>"); 4 function innerFn(){ 5 outerVar++; 6 document.write("Inner function\t"); 7 document.write("outerVar = "+outerVar+ "<br/>"); 8 } 9 return innerFn; 10 } 11 var fnRef=outerFn(); 12 fnRef(); 13 fnRef(); 14 15 var fnRef2=outerFn(); 16 fnRef2(); 17 fnRef2();
1 function outerFn(){ 2 var outerVar=0; 3 document.write("Outer function</br>"); 4 function innerFn1(){ 5 outerVar++; 6 document.write("Inner function 1 \t"); 7 document.write("outerVar = "+ outerVar+"</br>" ); 8 } 9 function innerFn2(){ 10 outerVar+=2; 11 document.write("Inner function 2 \t"); 12 document.write("outerVar = "+ outerVar+"</br>" ); 13 } 14 return {"fn1":innerFn1,"fn2":innerFn2}; 15 } 16 17 var fnRef=outerFn(); 18 fnRef.fn1(); 19 fnRef.fn2(); 20 fnRef.fn1(); 21 var fnRef2=outerFn(); 22 fnRef2.fn1(); 23 fnRef2.fn2(); 24 fnRef2.fn1();
//5,闭包之间的交互
// 对outerFn的后续调用会创建这些闭包的新实例,同时也会创建新的封闭环境,本质上是创建了一个新对象,自由变量就是这个实例的对象变量,而闭包就是这个对象的实例方法。