2

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 script:

$ cat test_this.js 
var x = 50;
console.log(x);
console.log(this.x);
console.log(this === global);
$ node test_this.js 
50
undefined
false

Not what I expected.

I don't really have a problem with the REPL behaving differently from a script, but where exactly in the Node documentation does it say something like "NOTE: when you run a script, the value of this is not set to global, but rather to ___________." Does anyone know, what this refers to in the global context when run as a script? Googling "nodejs this global context script" takes me to this page which looks very promising, as it describes contexts for running scripts, but it doesn't seem to mention the use of the this expression anywhere. What am I missing?

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • 1
    The phrase "*…initial value of this*" infers that you think it will change later. It can't. The value of *this* is set when entering an execution context, it can't be modified later. The question seems to be "*why isn't `this` within a module the global object?*". – RobG Jan 19 '15 at 06:26
  • FWIW I found an answer to my question [over here](http://stackoverflow.com/questions/6396467/a-puzzle-about-this-in-javascript-coffeescript) – Ray Toal Jan 19 '15 at 06:28
  • @RobG of course you are right, I have edited the question. (Also I actually didn't really pick up on the fact that running a simple script was indeed a module, though in retrospect I should have, then I could have more easily googled the answer or knew it was `exports` to begin with :) ). – Ray Toal Jan 19 '15 at 06:28

1 Answers1

5

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

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497