1

In interactive nodejs console:

> var a = 1;
> console.log(a);
1
> console.log(this.a);
1

so I think

a === this.a

But when I save it in a JS file and execute it, I get different response:

1 
undefined

Why this.a is undefined now?

limon
  • 907
  • 1
  • 9
  • 19

1 Answers1

1

When you are executing node from the console, 'this' refers to the global scope of the console. So 'a' automatically gets added to the global, just like declaring a variable in the browser in a similar way would add 'a' to window, i.e. window.a

When executing from the script, 'this' is an object. The variables are not added to the global scope in the same way. Why, I don't know. But this is what appears to be happening.

Geuis
  • 41,122
  • 56
  • 157
  • 219