title: How to access the correct `this` inside a callback
body: <p>I have a constructor function which registers an event handler:</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function MyConstructor(data, transport) {
      this.data = data;
      transport.on('data', function () {
          alert(this.data);
      });
  }
  
  // Mock transport object
  var transport = {
      on: function(event, callback) {
          setTimeout(callback, 1000);
      }
  };
  
  // called as
  var obj = new MyConstructor('foo', transport);</code></pre>
  </div>
  </div>
  </p>
  <p>However, I'm not able to access the <code>data</code> property of the created object inside the callback. It looks like <code>this</code> does not refer to the object that was created, but to another one.</p>
  <p>I also tried to use an object method instead of an anonymous function:</p>
  <pre><code>function MyConstructor(data, transport) {
      this.data = data;
      transport.on('data', this.alert);
  }
  
  MyConstructor.prototype.alert = function() {
      alert(this.name);
  };
  </code></pre>
  <p>but it exhibits the same problems.</p>
  <p>How can I access the correct object?</p>