title: Javascript: Class definition using Websocket
body: <p>I have a basic question about class definition in JavaScript. Let me explain my problem, here is my class (this is a simplified version for the sake of clarity):</p>
  <pre class="lang-js prettyprint-override"><code>var RemoteCursor = function(canvas_id) {
      this.ws_sendjoingroup = function() {
        console.log('Dummy log just for debug');
      }
      this.ws_cursor_onopen = function() {
        console.log('ws_cursor_on open: (debug)');
        this.ws_sendjoingroup();
      }
      this.ws_start_remote_cursor = function() {
          this.ws_remote_cursor = new WebSocket('ws://localhost/ws');
          this.ws_remote_cursor.onopen = this.ws_cursor_onopen;
      }
  }
  </code></pre>
  <p>I call this class inside my HTML page like this:</p>
  <pre class="lang-js prettyprint-override"><code>&lt;script&gt;
      window.onload = function() {
          var cursor1 = new RemoteCursor(&quot;usimage_cursor&quot;);
          cursor1.ws_start_remote_cursor();
      }
  &lt;/script&gt;
  </code></pre>
  <p>But when the <code>onopen</code> callback fires, inside the function <code>ws_cursor_onopen</code> the context is different, <code>this</code> have nothing defined and I got the error:</p>
  <blockquote>
  <p>Uncaught TypeError: this.ws_sendjoingroup is not a function!</p>
  <p>The typeof(this.ws_sendjoingroup) is undefined</p>
  </blockquote>
  <p>How can I pass the function inside my instance of <code>RemoteCursor</code> as the callback for the <code>onopen</code>?</p>