Javascript: this reference within a property function

This is intended to use on the browser.

function keyboardJS () {
    this.keys = {};
    this.tempASCIIkey;
    this.tempCHARkey;
}
keyboardJS.prototype = {
    keyIsUp : function (evt) {
      console.log(this);
      this.ASCIIkey = evt.keyCode;
      this.CHARkey = String.fromCharCode(this.ASCIIkey);
      this.keys[this.CHARkey] = false;
      console.log(this.CHARkey + " is now " + this.keys[this.CHARkey]);
    },
    keyIsDown : function (evt) {
      console.log(this);
      this.ASCIIkey = evt.keyCode;
      this.CHARkey = String.fromCharCode(this.ASCIIkey);
      this.keys[this.CHARkey] = true;
      console.log(this.CHARkey + " is now " + this.keys[this.CHARkey]);
    },
    init : function () {
      document.addEventListener("keydown", this.keyIsDown);
      document.addEventListener("keyup", this.keyIsUp);
    }
}

var game = {};

game.myKeyboard = new keyboardJS();
game.myKeyboard.init();

However, (console.log(this);) returns "#document". How do I reference the object's properties within a prototype function?

Upvotes: 1

Views: 102

Answers (1)

alex
alex

Reputation: 490667

Try this...

init : function () {
  document.addEventListener("keydown", this.keyIsDown.bind(this));
  document.addEventListener("keyup", this.keyIsUp.bind(this));
}

The this isn't magically bound when you pass a reference to a function, and in this context with addEventListener(), the this is what it is meant to be.

Note that bind() isn't supported by our favourite older IEs.

You can shim it, pass functions which call your functions on your prototype or use a library that has a bind equivalent (_.bind() in Underscore, $.proxy() in jQuery, etc).

Upvotes: 1

Related Questions