Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript global object vs window object

Tags:

javascript

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?

like image 691
Chaim Friedman Avatar asked Jun 29 '26 13:06

Chaim Friedman


1 Answers

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 something inside 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.

like image 84
Kirk Larkin Avatar answered Jul 02 '26 02:07

Kirk Larkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!