-1

Reading the book You-Don't-Know-JS and trying to understand the concept of this.

this is actually a binding that is made when a function is invoked, and what it references is determined entirely by the call-site where the function is called.

And I came across the below code:

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

var myVar = 1;
a();

The end result of the above code logged 1 which makes me wondering what is the call-site for the above code because clearly saw function b was being called inside function a and so I thought the expected value should be 2 instead of 1.

Rikin
  • 4,700
  • 2
  • 11
  • 20
SuicideSheep
  • 4,542
  • 15
  • 54
  • 99
  • "*…what it references is determined entirely by the call-site*" is not exactly true. A function's *this* may be set by *bind*, making the call irrelevant. Also, arrow functions adopt the *this* of their enclosing scope so if passed as closures, also obviate the call. – RobG May 04 '18 at 02:57

1 Answers1

-3

This is because all function belong to the global scope if they are defined with the keyword function, even if you may not be able to do this. Inside the a() function write it as the following.

this.b = function() {...}

That should give you what you are looking for.

31piy
  • 21,164
  • 6
  • 40
  • 57
  • 1
    "*all function belong to the global scope if they are defined with the keyword function*" is incorrect. Declared functions are scoped to their enclosing execution context, just like variables declared with *var*. – RobG May 04 '18 at 02:59