Reputation: 23
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?
Upvotes: 2
Views: 317
Reputation: 44916
The this
operator in JavaScript doesn't always follow the scoping rules you would expect.
This article will help to explain what is going on: http://unschooled.org/2012/03/understanding-javascript-this/
Upvotes: 1
Reputation: 129001
In JavaScript, this
is not tied down to an object by default; it is set by context. In this case, this
will be document
. One way to fix this is to bind the function such that this
will always be hero
:
document.onkeydown = hero.keyListener.bind(hero);
Note: bind
is only available in more recent browsers.
Upvotes: 2