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?