In Javascript, why is the "this" operator inconsistent?
<p>In JavaScript, the "this" operator can refer to different things under different scenarios. </p>

<p>Typically in a method within a JavaScript "object", it refers to the current object.</p>

<p>But when used as a callback, it becomes a reference to the calling object.</p>

<p>I have found that this causes problems in code, because if you use a method within a JavaScript "object" as a callback function you can't tell whether "this" refers to the current "object" or whether "this" refers to the calling object.</p>

<p>Can someone clarify usage and best practices regarding how to get around this problem?</p>

<pre><code>   function TestObject() {
            TestObject.prototype.firstMethod = function(){
                      this.callback();
                      YAHOO.util.Connect.asyncRequest(method, uri, callBack);

            }

            TestObject.prototype.callBack = function(o){
              // do something with "this"
              //when method is called directly, "this" resolves to the current object
              //when invoked by the asyncRequest callback, "this" is not the current object
              //what design patterns can make this consistent?
              this.secondMethod();
            }
            TestObject.prototype.secondMethod = function() {
             alert('test');
            }
        }
</code></pre>
