title: Javascript OOP: binding method to event handler
body: <p>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:</p>
  
  <pre><code>function Game() {
    // Class stuff
  
    this.handleClick = function(e) {
      alert(e);
    }
  
    // Bind event to method previously defined
    $('#board').bind('click', function(e) {
      this.handleClick(e);              // &lt;--- THIS IS THE PROBLEMATIC LINE
    });
  }
  </code></pre>
  
  <p>Now, if in the "problematic line" I write:</p>
  
  <pre><code>  handleClick(e)
  </code></pre>
  
  <p>I get <code>Uncaught ReferenceError: handleClick is not defined</code>.</p>
  
  <p>Instead, if I write:</p>
  
  <pre><code>  this.handleClick(e);
  </code></pre>
  
  <p>I get <code>Uncaught TypeError: Object #&lt;HTMLCanvasElement&gt; has no method 'handleClick'</code></p>
  
  <p>But then, if I do:</p>
  
  <pre><code>function Game() {
    // Class stuff
  
    this.handleClick = function(e) {
      alert(e);
    }
  
    var game = this;                    // &lt;--- I ASSIGN this TO board
    // Bind event to method previously defined
    $('#board').bind('click', function(e) {
      game.handleClick(e);              // &lt;--- THIS WORKS!! WHY????
    });
  }
  </code></pre>
  
  <p>It works!?!?!</p>
  
  <p>My questions are:</p>
  
  <ol>
  <li>Why does this happen this way? I know <code>this</code> can be problematic, but why assigning it to a variable changes it like that?</li>
  <li>Am I doing this wrong? Is there a better way to achieve something like this in a more elegant way?</li>
  </ol>