为什么 document.body 的事件处理程序中的 'this' 关键字引用全局 window 对象?

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>

我将 this 关键字放在按钮元素事件处理程序和 body 元素的另一个处理程序中,但第二个 this 关键字引用全局 window 对象。为什么?

document.getElementById('btn').onclick returns object HTMLButtonElement 因为 this 指的是被调用的对象。在本例中,它是按钮元素。

this 与作用域无关,与调用上下文有关。滚动时,您正在 body 元素上调用 this 。但是主体没有滚动,所以这将引用 returns window 的默认对象。 (Window 在浏览器中)。

这是因为 body 元素将 Window 对象的许多事件处理程序公开为事件处理程序内容属性。

此类事件目前为:blurerrorfocusloadresizescroll

这个列表叫做"Window-reflecting body element event handler set".

(参见,例如:https://html.spec.whatwg.org/dev/webappapis.html