title: javascript: prototypes with callbacks and 'this'
body: <p>I've create a prototype based class <code>Person</code> that opens a WebSocket connection and defines callback functions as prototype methods.</p>
  
  <p>Because inside the callback <code>this</code> will refer to the WebSocket object I used another variable to hold on to the <code>Person</code>'s <code>this</code>. However when I deal with multiple instances the variable gets overwritten.</p>
  
  <p>Here is a small snipped that shows the issue:</p>
  
  <pre><code>function Person(name){
      self = this
      self.name = name
  }
  
  Person.prototype = {
      getName : function(){
          return self.name
      },
  
      openConnection : function(host, port){
          self.pointCount = 0
          self.ws = new WebSocket("ws://" + host + ":" + port)
          self.ws.onopen = self.onOpenConnection
      },
  
      onOpenConnection : function()   {
          console.log(this) // prints the websocket
          console.log(self) // prints the person
          self.ws.send(self.name) // works only if one person exists
      }
  }
  
  var p1 = new Person("Jonh")
  var p2 = new Person("Adam")
  
  console.log(p1.getName()) // Prints Adam
  console.log(p2.getName()) // Prints Adam
  
  p1.openConnection("localhost", 7000) // opens connection for p1
  p2.openConnection("localhost", 7000) // opens another connection for p1    
  </code></pre>
  
  <p>If more than one <code>Person</code> is created, then when trying to send a message via the socket I get the following error:</p>
  
  <blockquote>
    <p>Uncaught Error: INVALID_STATE_ERR: DOM Exception 11</p>
  </blockquote>
  
  <p>So it seems that <code>self</code> is defined globally and my attempt to get a handle to the <code>Person</code>'s <code>this</code> inside the callback fails. Any suggestions on how to achieve that?</p>