1

I've read about closure and lexical environment and looked through the Stack to get the answer, but still couldn't find it. So, decided to make direct question.

Here it is the first situation:

function a() {
  this.counter = 1;

  function b() {
    this.counter = 2;
  }
  b();
  console.log(this.counter);
}
a(); // result 2

and second one:

function a() {
  this.counter = 1;

  function b() {
    this.counter = 2;
  }
  b();
  console.log(this.counter);
}
const b = {a: a};
b.a(); // result 1

Why we are receiving such results?
Maybe some could suggest decent resources to read for understanding how it works?

Volodymyr
  • 11
  • 2
  • In the first, `a` gets invoked with no calling context. In the second, `a` gets invoked with the calling context of the `b` object. The `b` function in both is invoked with no calling context, resulting in `window` being assigned to. – CertainPerformance Nov 26 '20 at 18:54

0 Answers0