Reputation: 6213
I have this function in Game.js
Game.prototype.onClick = function(event){
var x = event.x;
var y = event.y;
if (this.blueDeck[0].contains(x, y))
alert("Blue Deck Clicked");
}
OnClick gets called from this function in Main.js
canvas.addEventListener('mouseup', game.onClick, false);
and I have this function in Card.js
Card.prototype.contains = function(x, y){
return true;
}
The alert never comes up.
If I remove the if statement in onClick, the alert gets called.
Other functions like this.blueDeck[0].setDeckPos(w, h);
work fine when called in Game.js.
Why is contains not returning true?
Upvotes: 0
Views: 95
Reputation: 816422
The update confirms my assumption. this
will refer to the DOM element. The value of this
is determined on runtime, i.e. it depends on how the function is called, not where/how it was defined.
Either use a closure:
canvas.addEventListener('mouseup', function(event) {
game.onClick(event);
}, false);
or if you don't need access to the element, you can use .bind
[MDN] (see this link for a polyfill for browser with no native support):
canvas.addEventListener('mouseup', game.onClick.bind(game), false);
Learn more about this
:
this
(general)this
(emphasis on event handlers)Upvotes: 2
Reputation: 147403
A simple example of the OP works, so the error is elsewhere:
function Game(){
this.blueDeck = [new Card()];
}
Game.prototype.onClick = function(event){
var x;
var y;
if (this.blueDeck[0].contains(x, y))
alert("Blue Deck Clicked");
}
function Card(){}
Card.prototype.contains = function(x, y){
return true;
}
var g = new Game();
g.onClick(); // "Blue Deck Clicked"
When editing questions, please clearly mark the edit. See Felix's answer, the method isn't being called by an instance of Game but by an event listener. Remember that this is set by the call.
Upvotes: 0