首页 > 代码库 > this的指向

this的指向

 

 

this的指向:

1 //this 指的是调用 当前方法 (函数) 的那个对象
2 
3 function fn1(){
4    this;  
5 }
6 
7 //fn1();                                   this => window
8 //obj.onclick=fn1;                         this=>obj
9 //obj.onclick=function(){ this; }          this=>window;

 

this的应用:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8" />
 5         <title></title>
 6         <style type="text/css">
 7             *{margin: 0;padding: 0;}
 8             ul,li{list-style: none;}
 9             li { width:100px; height:150px; float:left; margin-right:30px; background:#f1f1f1; position:relative; z-index:1; }
10             div { width:80px; height:200px; background:red; position:absolute; top:75px; left:10px; display:none; }
11         </style>
12         <script type="text/javascript">
13             window.onload=function(){
14                 var  oUl=document.getElementById("ul1");
15                 var  aLi=oUl.getElementsByTagName("li");
16                 
17                 for(var i=0;i<aLi.length;i++){
18                     aLi[i].onmouseover=function(){
19                         this.getElementsByTagName("div")[0].style.display="block";
20                     };
21                     aLi[i].onmouseout=function(){
22                         this.getElementsByTagName("div")[0].style.display="none";
23                     };
24                 };
25             };
26         </script>
27     </head>
28     <body>
29         <ul id="ul1">
30             <li><div></div></li>
31             <li><div></div></li>
32             <li><div></div></li>
33             <li><div></div></li>
34         </ul>
35     </body>
36 </html>