Reputation: 77
<!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>
I put the this
keyword in a button element event handler and in another handler of the body element, but the second this
keyword referred to the global window object. Why?
Upvotes: 6
Views: 333
Reputation: 25322
That's because the body
element exposes as event handler content attributes a number of the event handlers of the Window object.
Such events are, currently: blur
, error
, focus
, load
, resize
and scroll
.
This list is called "Window-reflecting body element event handler set".
(See, for example: https://html.spec.whatwg.org/dev/webappapis.html)
Upvotes: 4
Reputation: 423
document.getElementById('btn').onclick
returns object HTMLButtonElement
because this
refers to the object that is being invoked. In this case, it is it the button element.
this
is not related to scope but to calling context. You are calling this
on the body element when scrolling. However the body is not scrolling, so this is going to reference the default object which returns the window. (Window in a browser).
Upvotes: 0