According to this explanation in MDN:
this
refers to the global objectYet, the following:
var globalThis = this;
function a() {
console.log(typeof this);
console.log(typeof globalThis);
console.log('is this the global object? '+(globalThis===this));
}
a();
... placed in file foo.js
produces:
$ nodejs foo.js
object
object
is this the global object? false
In Node.js, whatever code we write in a module will be wrapped in a function. You can read more about this, in this detailed answer. So, this
at the top level of the module will be referring to the context of that function, not the global object.
You can actually use global
object, to refer the actual global object, like this
function a() {
console.log('is this the global object? ' + (global === this));
}
a();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With