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!