var a = (function(){ var c= 0; return function(){ return ++c; } }()); var g = a(); console.log(g); var e= a(); console.log(e); var f = a(); console.log(f);//变量c不清零
通过闭包打印出li有几个节点
<ul id="test"> <li>1 <li>2 <li>3 <li>4 </ul>
var test = document.getElementById("test"), li = test.getElementsByTagName("li"); for(var i=0,len = li.length;i<len;i++){ li[i].onclick = function(num){ return function(){ console.log(++num); } }(i); }