Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`this` in global context and inside function

According to this explanation in MDN:

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

Yet, 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
like image 808
Marcus Junius Brutus Avatar asked Sep 24 '15 11:09

Marcus Junius Brutus


1 Answers

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();
like image 102
thefourtheye Avatar answered Sep 23 '22 15:09

thefourtheye