0

I am not able to understand the this keyword in Node.js

consider the code

var a=6
function fun(){
    var a=2;
    console.log(this);
    console.log(this.a);//undefined
    console.log("****",a);//2
}

fun();

In this a is defined at global scope and inside function fun().According to Scope rule of JavaScript a should return 2 and this.a should return 6 but in this code this.a is undefined where as a is 2.

Please explain the meaning of this in node.js and how it differs from this of javaScript.

Also, explain how to access the global a inside the function fun()

Ankit Halder
  • 135
  • 2
  • 14
  • 3
    If you declare a function using the `function` keyword, `this` refers to the function. However, you declared `a` as a variable in the function scope, not as a property. Please refer to this question : https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – Seblor Jul 18 '18 at 12:25
  • What in browser JavaScript would be the global scope in Node is the *module* scope. Leaving off `var` when initializing the global `a` (as in the code you initially posted) will actually work, because that will create a globally-scoped `a`. – Pointy Jul 18 '18 at 12:28
  • *"In this a is defined at global scope"* Not if this code is inside a module. *"According to Scope rule of JavaScript [...] this.a should return 6"* Only if the code is executed in *global scope* in non-strict mode. But that's not the case for node modules. – Felix Kling Jul 18 '18 at 12:28

0 Answers0