Cbas
Cbas

Reputation: 6213

JS function not returning value

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

Answers (2)

Felix Kling
Felix Kling

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:

Upvotes: 2

RobG
RobG

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"

Edit

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

Related Questions