I have this code:
function Keyboard() {
this.log = $('#log')[0];
this.pressedKeys = [];
this.bindUpKeys = function() {
$('body').keydown(function(evt) {
this.pressedKeys.push(evt.keyCode);
var li = this.pressedKeys[evt.keyCode];
if (!li) {
li = this.log.appendChild(document.createElement('li'));
this.pressedKeys[evt.keyCode] = li;
}
$(li).text('Down: ' + evt.keyCode);
$(li).removeClass('key-up');
});
}
this.bindDownKeys = function() {
$('body').keyup(function(evt) {
this.pressedKeys.push(evt.keyCode);
var li = this.pressedKeys[evt.keyCode];
if (!li) {
li = this.log.appendChild(document.createElement('li'));
}
$(li).text('Up: ' + evt.keyCode);
$(li).addClass('key-up');
});
}
}
I get these errors:
TypeError: 'undefined' is not an object (evaluating 'this.pressedKeys.push')
It doesn’t matter what I want to do with the Array, it just keeps giving me access errors, as if it doesn’t exists inside the prototype.
What am I doing wrong? 🙁 I’m just accessing the array as any other value inside the prototype). Are there problems with objects inside objects?
The problem is that inside the event handler
thisis not what you think. You can bind the event handler function with thebindmethod (or, since it looks like you’re using jQuery,$.proxy):Or you can store a reference to
thisoutside of the event handler e.g.