1

I'm learning about lexical scope and execution contexts in JS and came across a question.

My understanding of the keyword this may be limited, but I see that it references all variables in any function's current execution context.

Consider this example:

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

Here, I'll get a console log to myVar which will be assigned to the value 1.

Now for this example:

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

When function b is called, I see a reference to myVar, which is assigned to 100. Why isn't there a reference to myVar as assigned to 2?

Doesn't 'this' refer to the current function's lexical environment? In this case, function b is enclosed in function a and not the global environment.

Johnny G.
  • 337
  • 1
  • 4
  • 12

1 Answers1

4

Your understanding of this is completely wrong.

The value of this depends (usually) on how the function was called. (See How does the “this” keyword work? for details).

If you are:

  • in a browser
  • your JS isn't running in strict mode (which it should be)
  • the function is called with no explicit context

… then this will be the window object.


Normally, when a variable is declared, it exists only in the scope in which it was declared. It is not a property of any object.

There is one exception:

When a variable is declared in the global scope (i.e. outside of any function or without let or var inside a function) then it also becomes a property of the window object.


The effect you are seeing is the combination of those two things.

b(); has no context, so this is window. var myVar = 100; is outside of any function, so is a global and thus a property of window.

Community
  • 1
  • 1
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • isn't b under function a's context? therefore function b as a reference to its outer environment in function a? – Johnny G. Sep 28 '16 at 17:58
  • @user3882106 — No. As I said, context is determined by how a function is called, not where it is declared. See http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work . Don't confuse context and scope. – Quentin Sep 28 '16 at 18:06