简体   繁体   中英

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?

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 )

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM