Blog>
Snippets

Understanding 'this' in global scope

Show how 'this' refers to the global object in a non-strict global context.
<!DOCTYPE html>
<html>
<head>
    <title>Understanding 'this' in global scope</title>
</head>
<body>
    <script>
        // In a browser, the global scope is the window object
        console.log(this === window); // logs true, 'this' in the global scope references the global object which is 'window' in browsers

        function checkThis() {
            // In non-strict mode, 'this' also refers to the global object inside functions if they are called in the global scope
            console.log(this === window); // logs true
        }
        checkThis(); // calling function in the global scope

        // However, 'this' can be different in different contexts, such as inside an event handler
        document.body.addEventListener('click', function() {
            console.log(this === document.body); // logs true, 'this' inside the event handler refers to the element that received the event
        });
    </script>
</body>
</html>
This HTML file demonstrates 'this' in the global scope. The JavaScript is embedded within the HTML and shows the behavior of 'this'. In the global scope, 'this' refers to the global object, which is 'window' in browser environments. When a function is defined in the global scope and called in the global scope (non-strict mode), 'this' inside the function also refers to the global object. However, 'this' can change based on the context, such as within an event handler, where it refers to the element that the event was executed on.