2

I have the following code:

function foo(){
    console.log(this.a);
}

var a = 2;

foo(); 

The code above gives 2 when run in browser console. I run the same code in the terminal by doing node up-and-going.js and got undefined.

What am I missing?

PS: I'm new to JavaScript.

enter image description here

enter image description here

Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
lomse
  • 3,322
  • 6
  • 37
  • 62
  • The "default" scope/context in nodejs is different – Jonas Wilms Dec 05 '17 at 13:07
  • 1
    @charlieftl bad dupe, nodejs isnt mentioned at all – Jonas Wilms Dec 05 '17 at 13:09
  • @JonasW. https://stackoverflow.com/questions/20861049/this-different-between-repl-and-script https://stackoverflow.com/questions/25058814/what-does-this-mean-in-a-nodejs-module [Meaning of "this" in node.js modules and functions](https://stackoverflow.com/q/22770299/1048572)? – Bergi Dec 05 '17 at 13:13
  • I understand that in a browser, the `this` in my example refers to the browser global variable `window` since the function `foo();` was invoked globally. Can anyone tell me if I get it right? – lomse Dec 05 '17 at 13:21
  • @JonasW. any feedback on my comment? – lomse Dec 05 '17 at 13:27
  • 1
    @lomse yes, but that works differently in nodejs – Jonas Wilms Dec 05 '17 at 14:20

0 Answers0