2

I'm still learning JavaScript and when I tried to get an understanding of this behavior, I've got a little confused. One thing that I understand that this keyword is actually refer to where is the call-site of the function when it called. I was trying run the example code below:

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

The expected result is 2. It did show 2 on Chrome's console but when I tried to run it from NodeJS, result result would be undefined. my Node version is 6.10.1

Is the call-site will be different when the code run in Node compare to Browser's Console or is there anything that need my concern when I'm running code on nodeJS especially when using this keyword?

malxatra
  • 87
  • 7
  • 1
    Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – ponury-kostek Jun 09 '17 at 05:56
  • @ponury-kostek I'm not sure, but I didn't found any answer on that link related to my question why the behavior of `this` is different between browser and NodeJS console. The execution results will have different values compare to each other. – malxatra Jun 09 '17 at 06:06

2 Answers2

1

This is because default value for this in non-strict mode is window

Also when you define any variable outside a function, it becomes part of window.

Sample

function foo() {
  console.log(this.a);
  console.log(window.a);
}
var a = 2;
foo();

But if you try the same in strict mode(Like in node console), default value of this is undefined. So it will throw error when you try and access this.a

Sample

"use strict";
function foo() {
  console.log(this.a);
}
var a = 2;
foo();
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • Is there any similar value with `window` in nodeJS? means that let say If i want for `this` to refer global objects, how can it be done in NodeJS since it doesn't have `window`? – malxatra Jun 09 '17 at 06:13
  • You should not. If you want a global scope, create your own object and assign values to it. Also note that its a bad practice to bleed values to global scope. – Rajesh Jun 09 '17 at 06:15
1

In the browser your global object is the Window, "this" is referring to the window object. Every variable created in this execution context are attached to the Window object.
In NodeJS every variable defined outside of a specific execution context are attached to a "module" context which is considered the file you are working on and not to the global object that Nodes uses.

Therefore, the object invoking your function in the browser is the Window object and in node is the Global object. In the browser, your variable 'a' is attached to the Windows object and 'this' points to it. In Node 'a' is attached to the Module created for exporting the file but 'this' points to the Global object.

Check also this answer

MFAL
  • 1,090
  • 13
  • 19