<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
height: 1000px;
}
</style>
<title>Scroll</title>
</head>
<body>
<button id="btn">click</button>
<script type="text/javascript">
document.body.onscroll = function() {
alert(this);// displays [object Window], instead of [object HTMLBodyElement]
};
document.getElementById('btn').onclick = function() {
alert(this);// displays [object HTMLButtonElement]
}
</script>
</body>
</html>
我将this
关键字放在按钮元素事件处理程序中以及在body元素的另一个处理程序中,但是第二个this
关键字引用了全局窗口对象。为什么?
因为body
没有滚动,所以window
是。
这是因为body
元素将许多Window对象的事件处理程序公开为事件处理程序的内容属性。
此类事件当前为:blur
,error
,focus
,load
,resize
和scroll
。
此列表称为“窗口反射主体元素事件处理程序集”。
document.getElementById('btn').onclick
返回object HTMLButtonElement
,因为this
引用了正在调用的对象。在这种情况下,它就是按钮元素。
this
与范围无关,但与调用上下文有关。滚动时,您在body元素上调用this
。但是,主体没有滚动,因此将引用返回窗口的默认对象。 (浏览器中的窗口)。