Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the 'this' keyword inside event handlers of document.body refer to the global window object?

<!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?

like image 879
marcel Avatar asked Oct 16 '22 10:10

marcel


1 Answers

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)

like image 119
ZER0 Avatar answered Nov 12 '22 20:11

ZER0