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';
}

  

原文地址:https://www.cnblogs.com/PeriHe/p/7988728.html