`this` in the global context and inside the function

According to this explanation in MDN :

  • in a global context, this refers to a global object
  • in the context of a function, if the function is called directly, it again refers to the global object

However, 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 the foo.js file produces:

 $ nodejs foo.js object object is this the global object? false 
+5
source share
1 answer

In Node.js, any code that we write in a module will be wrapped in a function. You can learn more about this in this detailed answer . Thus, this at the top level of the module will refer to the context of this function, and not to the global object.

In fact, you can use the global object to refer to the actual global object, e.g.

 function a() { console.log('is this the global object? ' + (global === this)); } a(); 
+6
source

Source: https://habr.com/ru/post/1232181/


All Articles