Ad

Javascript Keydown Manipulating Object

- 1 answer

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?

Ad

Answer

  1. this.KeyDown,this.KeyUp will be undefined inside Control constructor, you need to move var control = new Control (); at the end.
  2. 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

Ad
source: stackoverflow.com
Ad