1

The code snippet says it all. I have a class and declare its variable in its constructor. The variable works fine inside the constructor, and when i make a new instance of the class, but the variable appears undefiend in the eventHandler.

"use strict";

class InputEngine{

    __mouseDown(event){
  alert(this.mouse); //doesn't work here
 };
 
 constructor(){
     this.mouse =3;
     window.addEventListener( 'mousedown', this.__mouseDown );
 }
}

let a = new InputEngine();
alert(a.mouse); //works here
<!DOCTYPE html>
<html>
<body>
<p>Click your mouse.</p>
</body>
</html>
Luka Kostic
  • 314
  • 3
  • 12

1 Answers1

0

The keyword this changes what it refers to based upon the current "operational context" the JavaScript runtime is executing. That means that when an event occurs, the event hander is operating in the context of that event - so this refers to the Event Object and not the object that happens to contain the event handler.

You have a couple of choices. The most direct, since your code does not do anything with the event, is to use bind to change the context for that function to the object containing it.

"use strict";

class InputEngine {

  __mouseDown(event) {
    console.log(event.type); // event is still available
    alert(this.mouse); //works
  };

  constructor() {
    this.mouse = 3;
    window.addEventListener('mousedown', this.__mouseDown.bind(this));
  }
}

let a = new InputEngine();
alert(a.mouse); //works here
<!DOCTYPE html>
<html>

<body>
  <p>Click your mouse.</p>
</body>

</html>
Randy Casburn
  • 13,840
  • 1
  • 16
  • 31
  • what do you mean 'does not do anything with the event' , and what are the other options? This is just test code to show my issue, the actual code has much more stuff – Luka Kostic Jan 20 '19 at 17:32
  • @LukaKostic - does any of that code use the variable you named `event` in your code? – Randy Casburn Jan 20 '19 at 17:34
  • Yes, gets the button which was pressed by event.which , and further code uses mousemove and gets the cursor location from event – Luka Kostic Jan 20 '19 at 17:35
  • other parts also use keydown, keyup , keypress and get which button was pressed – Luka Kostic Jan 20 '19 at 17:36
  • I've modified my answer to show you the event is still passed into the event handler - only the "context" is changed by the bind method. – Randy Casburn Jan 20 '19 at 17:40