zoukankan      html  css  js  c++  java
  • this的指向

    梳理一下this的指向问题:

    首先,如果在script标签中直接alert(this),我们可以看到,它是指向window的。

    <script type="text/javascript">
        alert(this); //[object Window]
    </script>
    

    window是js的老大,这里的 alert(this)其实就是window.alert(this);

    如果我们有一个像这样的函数并且调用它:

    function fn(){
        alert(this); 
    }
    		
    fn();     //[object Window]
    

    仍旧指向的是window,因为还是在window里调用的。fn()其实就是window.fn();

    因此我们可以这样理解:this指的是调用当前方法或函数的那个对象。谁动了函数,this就指向谁。

    如果我们创建一个按钮,并在点击时触发fn函数。这时候this就指向了按钮

    var oBtn = document.getElementById('btn');
    oBtn.onclick=fn;   //object HTMLInputElement
    

    还有一个很重要的概念就是“当前”(上面用红色标出来的)

    function fn(){
        alert(this); 
    }
    var oBtn = document.getElementById('btn');
    oBtn.onclick=function(){
        fn();    //[object Window]
    }

    这个例子中,是在点击时触发一个函数,在这个函数里面调用了fn;这个时候this就指向window。原因就出在当前上。

    Demo this :

    用this很简单就实现了div显示隐藏:

    <style>
    	li{  100px;height: 150px; float: left; margin-right: 30px; background: gray; position: relative; list-style: none; } 
    	div{  80px; height: 200px; background: pink; position: absolute; top: 75px; left: 10px; display: none; }
    </style>
    <script>
    	window.onload = function(){
    		var aLi = document.getElementsByTagName('li');
    		for( var i=0;i<aLi.length;i++ ){
    			aLi[i].onmouseover=function(){
    				this.getElementsByTagName('div')[0].style.display='block';
    			}
    			aLi[i].onmouseleave=function(){
    				this.getElementsByTagName('div')[0].style.display='none';
    			}
    		}
    
    	}
    </script>
    <body>
    	<ul>
    		<li><div></div></li>
    		<li><div></div></li>
    		<li><div></div></li>
    	</ul>
    </body>

    但如果我们把更改显隐状态放在另外的函数中,在鼠标滑过时来调用呢?根据上面分析,这样的话this是指向window的,大不到我们想要的效果。此时借助一个变量来将this存起来就好。如下:

    var aLi = document.getElementsByTagName('li');
    var that = null;
    for( var i=0;i<aLi.length;i++ ){
    	aLi[i].onmouseover=function(){
    		that = this;
    		show();
    	}
    	aLi[i].onmouseleave=function(){
    		this.getElementsByTagName('div')[0].style.display='none';
    	}
    }
    function show(){
    	that.getElementsByTagName('div')[0].style.display='block';
    }
    

      

  • 相关阅读:
    24.最优布线问题(kruskal算法)
    24.最优布线问题(kruskal算法)
    Algs4-1.4.11为StaticSETofInts添加一个实列方法howMany()
    Algs4-1.4.9预测程序运行时间
    Algs4-1.4.10二分查找找出元素所在的最小索引
    Algs4-1.4.7统计算术运算与比较次数
    Algs4-1.4.8计算输入文件中相等的整数对的数量
    Algs4-1.4.6给出以下代码段的运行时间的增长数量级
    Algs4- 1.4.4参照表1.4.4为TwoSum建立一和类似的表格
    Algs4-1.4.2修改ThreeSum防止两个int值相加可能溢出
  • 原文地址:https://www.cnblogs.com/PeriHe/p/7988728.html
Copyright © 2011-2022 走看看