Discussion: What’s This?
Execute the code to understand the output and gain insights into how the this keyword in JavaScript varies with context, while globalThis provides a standardized way to access the global object across different environments.
Verify the output
Now, it’s time to execute the code and observe the output.
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 ...