Skip to content Skip to sidebar Skip to footer

What Is The Context For `this` In Node.js When Run As A Script?

From the node REPL: $ node > var x = 50 > console.log(x) 50 > console.log(this.x) 50 > console.log(this === global) true Everything makes sense. However, when I have a

Solution 1:

In Node.js, as of now, every file you create is called a module. So, when you run the program in a file, this will refer the module.exports. You can check that like this

console.log(this === module.exports);
// true

As a matter of fact, exports is just a reference to module.exports, so the following will also print true

console.log(this === exports);
// true

Possibly related: Why 'this' declared in a file and within a function points to different object

Post a Comment for "What Is The Context For `this` In Node.js When Run As A Script?"