title: JavaScript: creating a reference to 'this' (e.g. 'var _this = this') vs. bind/call/apply
body: <p>Relying on <code>this</code> in the wrong context is a common pitfall. A contrived example:</p>
  
  <pre><code>function SomeClass() {
      this.prop = 42;
      document.body.addEventListener('click', function() {
          alert(this.prop); // will be undefined
      });
  }
  new SomeClass();
  </code></pre>
  
  <p>One way around this is using <code>bind</code> (or <code>call</code> or <code>apply</code>), for example:</p>
  
  <pre><code>function SomeClass() {
      this.prop = 42;
      document.body.addEventListener('click', (function() {
          alert(this.prop); // works
      }).bind(this));
  }
  new SomeClass();
  </code></pre>
  
  <p>Another option is to make a reference to <code>this</code> available via closure, usually <code>_this</code> or <code>self</code>:</p>
  
  <pre><code>function SomeClass() {
      var _this = this;
      this.prop = 42;
      document.body.addEventListener('click', function() {
          alert(_this.prop); // works
      });
  }
  new SomeClass();
  </code></pre>
  
  <p>I prefer the latter method, because I can declare it once rather than wrapping loads of functions with <code>bind()</code>, and nested callbacks (which I know are not ideal, but are seen in the wild) become simpler. But I have the sneaking suspicion that either a) there are gotchas with this method, or b) the fact that I have to do this or <code>bind</code> in the first place means that I'm doing it wrong. Any thoughts?</p>