What is the 'global' object in NodeJS

Arnab Das picture Arnab Das · Apr 26, 2017 · Viewed 34.3k times · Source

I've just seen a weird behaviour of the this keyword in NodeJS environment. I'm listing them with code. I've run this codes with NodeJS v6.x, with a single JavaScript file.

While testing with one line of code as follows, whether with or without the 'use strict' statement, this points to an empty object {}.

console.log(this)

But, when I'm running the statement within a self executing function like,

(function(){
  console.log(this);
}());

It's printing a really big object. Seems to me the Global execution context object created by NodeJS environment.

And while executing the above function with a 'use strict' statement, expectedly it's printing undefined

(function(){
  'use strict';

  console.log(this);
}());

But, while working with browser (I've tested only with Chrome), the first three examples yield the window object and the last one gave undefined as expected.

The behaviour of the browser is quite understandable. But, in case of NodeJS, does it not create the execution context, until I'm wrapping inside a function?

So, most of the code in NodeJS runs with an empty global object?

Answer

cнŝdk picture cнŝdk · Apr 26, 2017

While in browsers the global scope is the window object, in nodeJS the global scope of a module is the module itself, so when you define a variable in the global scope of your nodeJS module, it will be local to this module.

You can read more about it in the NodeJS documentation where it says:

global

<Object> The global namespace object.

In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node.js this is different. The top-level scope is not the global scope; var something inside an Node.js module will be local to that module.

And in your code when you write:

  • console.log(this) in an empty js file(module) it will print an empty object {} referring to your empty module.
  • console.log(this); inside a self invoking function, this will point to the global nodeJS scope object which contains all NodeJS common properties and methods such as require(), module, exports, console...
  • console.log(this) with strict mode inside a self invoking function it will print undefined as a self invoked function doesn't have a default local scope object in Strict mode.