-1

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?

3
  • 6
    Are you sure this refers to what you want it to? How/when are you calling the onClick method? this probably refers to something else (like the DOM element, which I'd assume this method is bound to) which does not have a blueDeck property and therefore throws an error. contains for sure returns true. Commented Aug 6, 2012 at 23:46
  • tip: beware of closures in js Commented Aug 6, 2012 at 23:49
  • 2
    You need to post a "working" example that demonstrates the behaviour. Commented Aug 6, 2012 at 23:49

2 Answers 2

2

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:

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.