title: Javascript: Promises + this
body: <p>Consider the following code:</p>
  
  <pre><code>foo: function() {
    var self = this;
    var p1 = p2 = someFunctionThatReturnsAPromise();
  
    Promise.all([p1, p2])
      .then(self.bar);
  }
  
  bar: function(promises) {
    var self = this;
    console.log(self);
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>undefined
  </code></pre>
  
  <p>But if I do the following instead:</p>
  
  <pre><code>foo: function() {
    var self = this;
    var p1 = p2 = someFunctionThatReturnsAPromise();
  
    Promise.all([p1, p2])
      .then(function(result) {
        self.bar(result);
      });
  }
  
  bar: function(promises) {
    var self = this;
    console.log(self);
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>{ foo: [Function],
    bar: [Function] }
  </code></pre>
  
  <p>I don't understand why the first call changes where <strong>this</strong> points in the bar function. Can someone enlighten me?</p>