First question here.
I’m trying Javascript objects. Here’s my code:
function main(){
document.onkeydown = hero.keyListener;
hero.move();
hero.counter();
}
var hero = {
dx: undefined,
dy: undefined,
keyListener: function (e) {
this.dy = 100;
},
move: function () {
this.dx = 80;
},
counter: function() {
document.getElementById("dxcounter").innerHTML = "Dx: "+ this.dx + " Dy: "+ this.dy;
}
};
The move method updates this.dx but keyListener does not update this.dy when a key is pressed.
It works if I change keyListener like this:
keyListener: function (e) {
that = hero;
that.dy = 100;
},
Why does the move method work for this but not the keyListener?
In JavaScript,
thisis not tied down to an object by default; it is set by context. In this case,thiswill bedocument. One way to fix this is to bind the function such thatthiswill always behero:Note:
bindis only available in more recent browsers.