再议js闭包

来源:互联网 发布:淘宝小二判决申诉 编辑:程序博客网 时间:2024/05/20 17:07

前两天去百度面试,被问到了这个问题:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head>  <title> new document </title>  <meta name="generator" content="editplus" />  <meta name="author" content="" />  <meta name="keywords" content="" />  <meta name="description" content="" />  <script type="text/javascript">  <!--   window.onload=function(){var btns=document.getElementsByTagName("input");for(var i=0;i<btns.length;i++){btns[i].onclick=(function(k){return function(){     alert(k);}})(i);}}//错误的写法/*window.onload=function(){var btns=document.getElementsByTagName("input");for(var i=0;i<btns.length;i++){                         btns[i].idx=i;btns[i].onclick=function(){                                 alert(this.idx+"|"+i);}}}*/     //-->  </script> </head> <body>  <input type="button" value="b1" /><br/>  <input type="button" value="b2" /><br/>  <input type="button" value="b3" /><br/>  <input type="button" value="b4" /><br/> </body></html>


今天查了查资料,问了下公司里专业的js程序员,大概搞清楚了这个问题,就是如上的两种写法,一种错误的,一种正确的,但是说实话,还是感觉有点晕。

有清楚的同学给详细解释一下吧。

原创粉丝点击