1. 程式人生 > >this的指向

this的指向

我們 隱藏 btn mar 裏的 更改 input 鼠標 lock

梳理一下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{ width: 100px;height: 150px; float: left; margin-right: 30px; background: gray; position: relative; list-style: none; } 
	div{ width: 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‘;
}

  

this的指向