0

I'm a novice in JS (I'm also learning React) and my question is related to the two different values that "this" keyword takes in the following code:

var logseeger = {
    a: console.log('>> this: ', this), // window
    x: 0,
    updateCount: function(){
        this.x++; // x=1
        console.log('updateCount: ', this); // implicit binding: logger | from event: button
        console.log('>> x: ', this.x); // implicit binding: x=1 | from event: NaN
    }
}

console.log('top of the calling')
logger.updateCount()

// WHY inside logger "this" takes the scope from the button
document.querySelector('#btn').addEventListener('click', logger.updateCount);

As you can see, if I call updateCount() method from logger objetc, "this" outside the function takes the value from window and inside the function it takes the value of logger. But all becomes weird for me when I click te button and I see that "this" takes the value of the button. For this I get "NaN".

I know if I want to make it works, I should pass a callback to addEventListener but what I want to learn here is how it works.

Thanks!

Pablo N
  • 21
  • 4
  • _"I know if I want to make it works, I should pass a callback to addEventListener"_ - `logger.updateCount` is one... ;) – Andreas Jan 21 '20 at 12:24
  • 1
    [How does the “this” keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Andreas Jan 21 '20 at 12:24

1 Answers1

0

For me thinking about the scope of "this" is most relevant to think about the outer scope of the surrounding closure or object or I also call it "environment". So in your first console.log of "this" the surrounding closure is pointing to the global window object which surrounds the logger instance. Your second console.log of "this" is inside a method of the logger object so it points to the object itself. The object is ("surrounding" the method) and in the third one you are not calling the method but leave the calling to and external api. You just passing a reference to your function so somebody else is surrounding the function now and passing the "this" to its environment when it will be executed.