Given the following code snippet.
var name = 'John';
function foo() {
console.log(this.name);
}
foo();
Why is it that when I run this code in the browser the log outputs the name, but when I run this same code snippet in node it outputs undefined?
In the browser this refers to the window object, and the global variable will get attached to the window. Now in node this will refer to the global object in this example, so does my global variable not get attached to the global object as it does in the browser when it gets attached to the window?
The Node.js global works differently to the global scope in a browser. See the definition of global for more:
In browsers, the top-level scope is the global scope. This means that within the browser var something will define a new global variable. In Node.js this is different. The top-level scope is not the global scope;
var somethinginside a Node.js module will be local to that module.
This question may also be helpful: Meaning of "this" in node.js modules and functions.
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