this 是一个棘手的话题。 this 指的是您当前在其中工作的函数的“所有者”。根据它所处的上下文或 范围,this 可能意味着几个不同的东西。通常,它指的是window 对象,它负责跟踪您的大部分javascript 变量,并包含几个函数。这样做的原因是因为除非它们被明确定义,否则每个 javascript 函数(和变量)的所有者都是window。换句话说,以下是正确的:
<script type="text/javascript">
var something = "Hey";
this.something === something; //these will evaluate to true, because when you
window.something === something; //declared the variable `something`, it was assigned
this === window; //to the window object behind the scenes.
</script>
不过,它并不总是引用window。在事件处理程序中,this 通常指的是触发事件的element。我不想深入探讨事件处理程序,但这里有一个使用jQuery 的示例。旁注——了解 jQuery 的来龙去脉。
HTML:
<div id="myDiv"></div>
Javascript:
<script type="text/javascript">
$('#myDiv').bind("click",function() {
$(this).css("visibility","hidden");
});
</script>
在本例中,this 指的是顶部框中的 html 元素。 $() 在它周围,因为这是为元素创建 jQuery 对象的语法。我这样做是为了能够使用css 函数,但我也可以轻松地完成类似this.style.visibility = "hidden"; 的操作
上面例子中this之所以提到元素,是因为在幕后,jQuery的bind方法正在做这样的事情:
var ele = document.getElementById("myDiv");
ele.onclick = function(){ //the same function as above, but with all the
//behind-the scenes stuff that jquery does to create a jQuery
//object
};
请注意,因为我们将函数分配给 ele.onclick,所以函数“属于”元素 ele。因此,在该函数内部,this 应该引用ele。
如果有什么我遗漏的内容你还不太明白,请告诉我。