Reputation: 357
I'm trying to make an object handling keyboard inputs from the user.
var control = new Control ();
function Control () {
this.w = 0;
this.a = 0;
this.s = 0;
this.d = 0;
document.addEventListener("keydown", this.KeyDown);
document.addEventListener("keyup", this.KeyUp);
}
Control.prototype.KeyDown = function (event, control) {
switch (event.keyCode) {
case 87:
this.w = 1;
break;
case 65:
this.a = 1;
break;
case 83:
this.s = 1;
break;
case 68:
this.d = 1;
break;
}
console.log("w: " + this.w + "\na: " + this.a + "\ns: " + this.s + "\nd: " + this.d);
}
Control.prototype.KeyUp = function (event) {
switch (event.keyCode) {
case 87:
this.w = 0
break;
case 65:
this.a = 0;
break;
case 83:
this.s = 0;
break;
case 68:
this.d = 0;
break;
}
console.log("w: " + this.w + "\na: " + this.a + "\ns: " + this.s + "\nd: " + this.d);
}
The problem is that whenever I write "this" inside the "keyDown", and "keyUp" functions, "this" refers to the document, and not the "control" object. How do I access the "control" object from within the functions?
Upvotes: 0
Views: 153
Reputation: 7803
Move var control = new Control ();
to the end of your script. Functions in prototype have not been defined yet when you are trying to use them right now.
Then, you can bind the function to the context you want.
document.addEventListener("keydown", this.KeyDown.bind(this));
document.addEventListener("keyup", this.KeyUp.bind(this));
See this fiddle.
There are other options as well, but in your case, bind
would be easier. For more information take a look at the answer on this question.
Upvotes: 0
Reputation: 7742
this.KeyDown,this.KeyUp
will be undefined
inside Control
constructor, you need to move var control = new Control ();
at the end.You can bind control
context using below code.
document.addEventListener("keydown", this.KeyDown.bind(this));
document.addEventListener("keyup", this.KeyUp.bind(this));
Note: bind is not supported in IE8, alternative is here
Upvotes: 1