skip to Main Content

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


  1. 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 🙂

    Login or Signup to reply.
  2. 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 to global or globalThis like you might expect, but to module.exports by default. However, in ECMAScript modules (those with file extension .mjs or if Node.js is run with the --experimental-modules flag or type=module in package.json), this at the top level is undefined.

    // this in a .js file in Node.js
    console.log(this === global); // false
    console.log(this === module.exports); // true
    
    // this in a .mjs file or inside an ECMAScript module in Node.js
    console.log(this); // undefined
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search