1

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?

Chaim Friedman
  • 5,308
  • 2
  • 27
  • 49
  • Possible duplicate of [What does "this" mean in a nodejs module?](https://stackoverflow.com/questions/25058814/what-does-this-mean-in-a-nodejs-module) – jmargolisvt Sep 01 '17 at 19:06
  • When I run it in node, I get the `John` as the output. – Ted Hopp Sep 01 '17 at 19:06
  • could that be a versioning issue? This is my node version v7.7.4 – Chaim Friedman Sep 01 '17 at 19:08
  • Dunno about versioning. I'm running v8.4.0 on a Mac, but I also ran your code on node v6.9.1 on another machine. Are you running the code in a plain vanilla node session or doing something inside a module? – Ted Hopp Sep 01 '17 at 19:17

2 Answers2

2

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.

Kirk Larkin
  • 60,745
  • 11
  • 150
  • 162
-2

You shouldn't use this because it refers to the global scope object. In browsers it is document. If you want to access your variable, just write its name. With operator . you access property of an object.