I know I'm making a mistake here but I can't figure out what it is.
The following code (non-strict mode) works as I expect in a browser and outputs "hello" to the console.
function a() {
console.log(this.bar);
}
var bar = "hello";
a();
But when I run it in node "undefined" is the output.
Does anyone know the reason?
In both, the browser and Node, this
inside the function refers to the global object (in this case). Every global variable is a property of the global object.
The code works in the browser because the "default scope" is the global scope. var bar
therefore declares a global variable, which becomes a property of the global object.
However in Node, every file is considered to be a module. Each module has its own scope. In this case,var bar
does not create a global variable, but a module scoped variable. Since there is no global variable bar
, this.bar
is undefined
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With