5

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
Marcus Junius Brutus
  • 23,022
  • 30
  • 155
  • 282

1 Answers1

6

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();
Community
  • 1
  • 1
thefourtheye
  • 206,604
  • 43
  • 412
  • 459
  • Given that `a` is called from within the module though, shouldn't it stil be the same inside and outside the function? – James Thorpe Sep 24 '15 at 11:18
  • @JamesThorpe `a` is called without any context object (`this`). So, by default `this` will refer the global object only. – thefourtheye Sep 24 '15 at 11:19