2

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

Running it in NodeJS (v16.19.1) in WSL 2 (windows 10) Is there an explanation for this? Thank you!

geeky01adarsh
  • 312
  • 3
  • 14
Dinh Minh Luu
  • 71
  • 4
  • 7
  • 1
    Where are you running it? I get `this === globalThis //true` – evolutionxbox Jun 30 '23 at 09:45
  • I think you should compare to global instead if globalThis – Dawid Jun 30 '23 at 09:45
  • 1
    It isn't clear if the code you are running is on the REPL, in a CommonJS module or in an ECMAScript module. Context matters. – Quentin Jun 30 '23 at 09:46
  • I have compared "this" to both "globalThis" & "global". I am running NodeJS (v16.19.1) in WSL 2 (windows 10). – Dinh Minh Luu Jun 30 '23 at 09:47
  • 2
    In a CommonJS or ES Module, [a module is **not** in the global scope, unlike most scripts in a browser](https://nodejs.org/docs/latest-v20.x/api/globals.html#global). That's why `global` (deprecated) and `globalThis` exist. – RickN Jun 30 '23 at 09:56
  • You stumbled upon one of the most confusing aspects of javascript. But generally speaking `this` should refer to your current context. You can always test it out by using `console.log(this)`. The first question you should ask yourself is why you need it at all? – Kokodoko Jun 30 '23 at 10:02

1 Answers1

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

Jagajit Prusty
  • 2,070
  • 2
  • 21
  • 39
geeky01adarsh
  • 312
  • 3
  • 14
  • Both node.js and browsers implement the same ECMAScript `GetThisBinding`, why would they return anything different? – Bergi Jun 30 '23 at 10:07
  • @Bergi In browsers `this` keyword finds its value from `ResolveThisBinding()`, however, ECMAScript does this for `global`. – geeky01adarsh Jun 30 '23 at 10:13