Hello!
I want to assign listeners when creating an object:

class ListenerClass{ constructor(){ document.addEvetListener('mousedown', function(event){ this.consoleCoordinate(event); }) } consoleCoordinate(event){ console.log('x:' + event.clientX); } } 

At the exit with every click I get an error that consoleCoordinate is not a function. Of course, because this in this.consoleCoordinate relevant to the context of addEventListener .
It's clear...
The question is - how do you pass this method to addEventListener in the constructor now?

    1 answer 1

      document.addEvetListener('mousedown', (function(event){ this.consoleCoordinate(event); }).bind(this)) 

    or

      document.addEvetListener('mousedown', event => { this.consoleCoordinate(event); }) 
    • I think the second option is preferable, because lexically tied to the class - korytoff
    • Just super! Thank you very much!!!!!! - OO
    • The second option is not fully understand. I think the first is more correct - here we use the method that is just needed in order to explicitly bind the class context to the handler: msdn.microsoft.com/ru-ru/library/dn569317(v=vs.94).aspx - OO
    • Eh ... Well. I found a reason to sleep, but now I’ll have to learn all night again ... - OO
    • @OO are both correct. Arrow functions (in them this is the same as in the code in which they are defined) appeared in ES6. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - Igor