Value of this in a node module:
this in NodeJS global scope is the current module.exports object, not the global object. This is different from a browser where the global scope is the global window object. Consider the following code executed in Node:
console.log(this); // logs {}
module.exports.foo = 5;
console.log(this); // log { foo:5 }
First we log an empty object because there are no values in module.exports in this module. Then we put foo on the module.exports object, when we then again log this we can see that it now logs the updated module.exports object.
How can we access the global object:
We can access the global object in node using the global keyword:
console.log(global);
The global object exposes a variety of useful properties about the environment. Also this is the place where functions as setImmediate and clearTimeout are located.
Value of this in a node module:
this in NodeJS global scope is the current module.exports object, not the global object. This is different from a browser where the global scope is the global window object. Consider the following code executed in Node:
console.log(this); // logs {}
module.exports.foo = 5;
console.log(this); // log { foo:5 }
First we log an empty object because there are no values in module.exports in this module. Then we put foo on the module.exports object, when we then again log this we can see that it now logs the updated module.exports object.
How can we access the global object:
We can access the global object in node using the global keyword:
console.log(global);
The global object exposes a variety of useful properties about the environment. Also this is the place where functions as setImmediate and clearTimeout are located.
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,thiswill point to the global nodeJS scope object which contains all NodeJS common properties and methods such asrequire(),module,exports,console...console.log(this)with strict mode inside a self invoking function it will printundefinedas a self invoked function doesn't have a default local scope object in Strict mode.