js中this与srcElement的区别

   对于js初学着必须理解this和srcElement的应用,这也是面试中经常考到的。

  this:

  下面先看一个例子:

 1 <html>
 2  <title>this与srcElement的区别</title>
 3 <head>
 4  <script type="text/javascipt>"
 5  function btnClick(){
 6   alert(this.value);
 7 }
 8 </script>
 9 </head>
10 <body>
11  <input type="button" value="单击" onclick="btnClick()"/>
12 </body>
13 </html>

 此时弹出的答案为“undefined”,说明在调用函数时不能使用this.属性来获取。再看下一个例子:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml" >
 3 <head>
 4     <title>无标题页</title>
 5     <script type="text/javascript">
 6      function btnClick(btn){
 7       alert(btn.value);
 8      }
 9     </script>
10 </head>
11 <body>
12 <input type="button" onclick="btnClick(this)" value="单击" />
13 
14 </body>
15 </html>

此时得出的答案为“单击”,此时为什么可以呢?从代码中可以看出,在onclick事件调用函数btnClick()时,将this当作参数传递给了函数。

综合以上:在函数调用时不能直接使用this.属性来获取,而必须将this当作参数传递。

 window.event.srcElement:

下面看一个例子:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml" >
 3 <head>
 4     <title>无标题页</title>
 5     <script type="text/javascript">
 6      function btnClick(){
 7       alert(window.event.srcElement.value);
 8      }
 9     </script>
10 </head>
11 <body>
12 <input type="button" onclick="btnClick()" value="单击" />
13 
14 </body>
15 </html>

此时得出的答案为“单击”,说明在调用函数时可以使用window.event.srcElement.属性来获取。

为什么this不能直接使用而window.event.srcElement可以直接使用呢?从单纯的字面上说this的意思是“当前”。在函数调用时,没有指定具体是哪一个控件,在函数中直接用this是不可以的。在第二段代码中就将this当成了参数传递,所以能得出正确的答案。

 

其实this和window.event.srcElement的使用区别是:如果要直接使用this.属性,此时的函数不能是被调用的而必须是响应函数,而window.event.srcElement则无此限制。

 

 

 

 

 

 

 

posted @ 2012-05-23 01:18  孙进  阅读(3172)  评论(0编辑  收藏  举报