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?
Try this…
The
thisisn’t magically bound when you pass a reference to a function, and in this context withaddEventListener(), thethisis 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).