标签:
1 function checkClosure(){
2 var str = ‘rain-man‘;
3 setTimeout(
4 function(){ alert(str); } //这是一个匿名函数
5 , 2000);
6 }
7 checkClosure();
1 function f1(){
2 var n=999;
3 nAdd=function(){n+=1}
4 function f2(){
5 alert(n);
6 }
7 return f2;
8 }
9 var result=f1();
10 result(); // 999
11 nAdd();
12 result(); // 1000
1 function forTimeout(x, y){
2 alert(x + y);
3 }
4 function delay(x , y , time){
5 setTimeout(‘forTimeout(‘ + x + ‘,‘ + y + ‘)‘ , time);
6 }
7 /**
8 * 上面的delay函数十分难以阅读,也不容易编写,但如果使用闭包就可以让代码更加清晰
9 * function delay(x , y , time){
10 * setTimeout(
11 * function(){
12 * forTimeout(x , y)
13 * }
14 * , time);
15 * }
16 */
17
1
2 var oEvent = {};
3 (function(){
4 var addEvent = function(){ /*代码的实现省略了*/ };
5 function removeEvent(){}
6 oEvent.addEvent = addEvent;
7 oEvent.removeEvent = removeEvent;
8 })();
1 /**
2 * <body>
3 * <ul>
4 * <li>one</li>
5 * <li>two</li>
6 * <li>three</li>
7 * <li>one</li>
8 * </ul>
9 */
10
11
12 var lists = document.getElementsByTagName(‘li‘);
13 for(var i = 0 , len = lists.length ; i < len ; i++){
14 lists[ i ].onmouseover = function(){
15 alert(i);
16 };
17 }
1 //使用立即执行函数
2 var lists = document.getElementsByTagName(‘li‘);
3 for(var i = 0 , len = lists.length ; i < len ; i++){
4 (function(index){
5 lists[ index ].onmouseover = function(){
6 alert(index);
7 };
8 })(i);
9 }
10 //或者
11 function eventListener(list, index){
12 list.onmouseover = function(){
13 alert(index);
14 };
15 }
16 var lists = document.getElementsByTagName(‘li‘);
17 for(var i = 0 , len = lists.length ; i < len ; i++){
18 eventListener(lists[ i ] , i);
19 }
标签:
原文地址:http://www.cnblogs.com/gsh-beibei/p/5601891.html