title: Javascript: callback context between class borders
body: <p>I have a problem with the contexts of callbacks and javascript classes.
  Basically, I know that inside a callback function body, the this-argument is undefined and therefore we need some tricks like the introduction of a additional self-argument.</p>
  <p>However, in my code I have two layers of indirection and I really cannot get things figured out.</p>
  <p>OK, here's my task:
  I'm writing a class for doing some fancy stuff on some data.
  The data comes from http-requests, and I want the network logic and json parsing to be encapsulated in a different class (a generic communication class which can be used elsewhere).</p>
  <p>This means:</p>
  <ul>
  <li>myFancyClass creates an instance of myCommunicationClass</li>
  <li>myFancyClass triggers network request via myCommunicationClass</li>
  <li>because the network request is async, myCommunicationClass has to inform myFancyClass when the data is ready via callback
  And this is where I'm lost.</li>
  </ul>
  <p>example code:</p>
  <pre><code>class myFancyClass {
  
          indicationCallback(data) {
              /* store the data*/
              this.data=data; // This is not working!!
          }
  
      doSomeStuff() {
          this.conn = new myCommunicationClass(ip, port, indicationCallback);
          this.conn.ExecuteRequest();
      }
  }
  
  
  class myCommunicationClass{
      constructor(ip, port, callback) {
          /* remember callback for later use */
          this.callback = callback;
      }
  
      ExecuteRequest() {
          /* set up request options */
          var self = this;
          request.post(options, function(error, response, body) {
                  /* check for errors, otherwise call callback*/
                  self.callback(receivedData)
          }
      }
  }
  </code></pre>
  <p>As you can see, I'm already familiar with the &quot;self = this-trick&quot;.
  However, when myCommunicationClass calls the callback, the context of the myFancyClass  object is no longer valid.</p>
  <p>To some it up: I have callbacks and I have two classes involved, which makes it even harder (for me) to get the right contexts figured out.
  Whats your approach on this?</p>