I am having trouble understanding "this" keyword behaviors in JavaScript (NodeJS – v16.19.1). According to this site, "this" keyword in the global execution context will reference the global object:
// this is my entire index.js file, I run "node index.js"
// global scope
console.log(this === globalThis); // this should be true but it is false.
console.log(this); // undefined
Is there an explanation for this? Thank you!
2
Answers
This behavior is because when a module file is called then
this
get binned to the return value of GetThisBinding(), which return undefined.However, if you will run the same code on browser then it will return true.
Hope it helps 🙂
In Node.js, each file is its own module and has its own separate scope. When you use
this
at the top level in a Node.js module (outside any functions), it doesn’t point toglobal
orglobalThis
like you might expect, but tomodule.exports
by default. However, in ECMAScript modules (those with file extension.mjs
or if Node.js is run with the--experimental-modules
flag ortype=module
inpackage.json
),this
at the top level isundefined
.