Search⌘ K
AI Features

Discussion: What’s This?

Understand the different behaviors of the this keyword in JavaScript, including strict vs. non-strict modes, object methods, constructor functions, and explicit bindings. Learn how to use globalThis for consistent access to the global object across environments, improving code portability and robustness.

Verify the output

Now, it’s time to execute the code and observe the output.

Javascript (babel-node-es2024)
let key = 2049;
(function() {
"use strict";
console.log(this.key);
})();

The this binding: Strict vs. non-strict mode

The this keyword in JavaScript can be a bit tricky because its value depends on where the code is running and how it’s being used. If we run the code outside of any specific function or object, this refers to the global object. In a web browser, the global object is usually window, and in Node.js, it’s global. So, if we run console.log(this) in a web browser’s console, we’ll see the value of window printed out.

But here’s the interesting part: the value of this can change depending on the context. If we’re inside a function that is not part of an object, then this might be different. In ...