I'm new to JS and I understand functions are the way to declare "class like" structures. I'm trying to do something like this:
function Game() {
  // Class stuff
  this.handleClick = function(e) {
    alert(e);
  }
  // Bind event to method previously defined
  $('#board').bind('click', function(e) {
    this.handleClick(e);              // <--- THIS IS THE PROBLEMATIC LINE
  });
}
Now, if in the "problematic line" I write:
  handleClick(e)
I get Uncaught ReferenceError: handleClick is not defined.
Instead, if I write:
  this.handleClick(e);
I get Uncaught TypeError: Object #<HTMLCanvasElement> has no method 'handleClick'
But then, if I do:
function Game() {
  // Class stuff
  this.handleClick = function(e) {
    alert(e);
  }
  var game = this;                    // <--- I ASSIGN this TO board
  // Bind event to method previously defined
  $('#board').bind('click', function(e) {
    game.handleClick(e);              // <--- THIS WORKS!! WHY????
  });
}
It works!?!?!
My questions are:
- Why does this happen this way? I know thiscan be problematic, but why assigning it to a variable changes it like that?
- Am I doing this wrong? Is there a better way to achieve something like this in a more elegant way?
 
    