-3

I don't completely understand how this works. For example,

var logger = {
x: 0,
updateCount: function(){
    this.x++;
    console.log(this.x);
    }
}  

Now, from what I've read, the value of this when updateCount is called as a property of logger should be logger. So why doesn't the code below work?

document.querySelector('button').addEventListener('click', logger.updateCount);

Also, why does this work?

document.querySelector('button').addEventListener('click', function(){
logger.updateCount();

});

1 Answers1

0

In the first one, you are passing a function as a parameter, and it is called over there. Therefore the caller will not be logger. And "this" depends on the caller. On the second one as you can see, you are calling the function from the logger, so "this" is logger.

You can modify the first as follows, so that its "this" is set as logger.

document.querySelector('button').addEventListener('click', logger.updateCount.bind(logger));
Nuri Tasdemir
  • 9,285
  • 2
  • 36
  • 60