<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>

[{'answer_id': 80095, 'author': 'Ash', 'author_id': 5023, 'author_profile': 'https://Stackoverflow.com/users/5023', 'pm_score': 0, 'selected': False, 'text': '<p>I believe this may be due to how the idea of [closures](<a href="http://en.wikipedia.org/wiki/Closure_(computer_science)" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Closure_(computer_science)</a> work in Javascript.</p>\n\n<p>I am just getting to grips with closures myself.  Have a read of the linked wikipedia article.</p>\n\n<p>Here\'s <a href="http://www.javascriptkit.com/javatutors/closures.shtml" rel="nofollow noreferrer">another article</a> with more information.</p>\n\n<p>Anyone out there able to confirm this?</p>\n'}, {'answer_id': 80119, 'author': 'dimarzionist', 'author_id': 10778, 'author_profile': 'https://Stackoverflow.com/users/10778', 'pm_score': 0, 'selected': False, 'text': "<p>As soon as callback methods are called from other context I'm usually using something that I'm call callback context:</p>\n\n<pre><code>var ctx = function CallbackContext()\n{\n_callbackSender\n...\n}\n\nfunction DoCallback(_sender, delegate, callbackFunc)\n{\n ctx = _callbackSender = _sender;\n delegate();\n}\n\nfunction TestObject()\n{\n   test = function()\n  {\n     DoCallback(otherFunc, callbackHandler);\n  }\n\n  callbackHandler = function()\n{\n ctx._callbackSender;\n //or this = ctx._callbacjHandler;\n}\n}\n</code></pre>\n"}, {'answer_id': 80127, 'author': 'Ricky', 'author_id': 653, 'author_profile': 'https://Stackoverflow.com/users/653', 'pm_score': 5, 'selected': True, 'text': "<p>In JavaScript, <code>this</code> always refers to the object invoking the function that is being executed. So if the function is being used as an event handler, <code>this</code> will refer to the node that fired the event. But if you have an object and call a function on it like:</p>\n\n<pre><code>myObject.myFunction();\n</code></pre>\n\n<p>Then <code>this</code> inside <code>myFunction</code> will refer to <code>myObject</code>. Does it make sense?</p>\n\n<p>To get around it you need to use closures. You can change your code as follows:</p>\n\n<pre><code>function TestObject() {\n    TestObject.prototype.firstMethod = function(){\n        this.callback();\n        YAHOO.util.Connect.asyncRequest(method, uri, callBack);\n    }            \n\n    var that = this;\n    TestObject.prototype.callBack = function(o){\n        that.secondMethod();\n    }\n\n    TestObject.prototype.secondMethod = function() {\n         alert('test');\n    }\n}\n</code></pre>\n"}, {'answer_id': 80159, 'author': 'Shog9', 'author_id': 811, 'author_profile': 'https://Stackoverflow.com/users/811', 'pm_score': 2, 'selected': False, 'text': "<p><code>this</code> corresponds to the context for the function call. For functions not called as part of an object (no <code>.</code> operator), this is the global context (<code>window</code> in web pages). For functions called as object methods (via the . operator), it's the object.</p>\n\n<p>But, you can make it whatever you want. All functions have .call() and .apply() methods that can be used to invoke them with a custom context. So if i set up an object Chile like so:</p>\n\n<pre><code>var Chile = { name: 'booga', stuff: function() { console.log(this.name); } };\n</code></pre>\n\n<p>...and invoke Chile.stuff(), it'll produce the obvious result:</p>\n\n<pre><code>booga\n</code></pre>\n\n<p>But if i want, i can take and <em>really screw with it</em>:</p>\n\n<pre><code>Chile.stuff.apply({ name: 'supercalifragilistic' });\n</code></pre>\n\n<p>This is actually quite useful...</p>\n"}, {'answer_id': 80177, 'author': 'jeannicolas', 'author_id': 14981, 'author_profile': 'https://Stackoverflow.com/users/14981', 'pm_score': 0, 'selected': False, 'text': "<p>You can also use Function.Apply(<em>thisArg</em>, <em>argsArray</em>)... Where thisArg determines the value of <em>this</em> inside your function...the second parameter is an optional arguments array that you can also pass to your function. </p>\n\n<p>If you don't plan on using the second argument, don't pass anything to it. Internet Explorer will throw a TypeError at you if you pass <em>null</em> (or anything that is not an array) to function.apply()'s second argument...</p>\n\n<p>With the example code you gave it would look something like:</p>\n\n<pre><code>YAHOO.util.Connect.asyncRequest(method, uri, callBack.Apply(this));\n</code></pre>\n"}, {'answer_id': 80478, 'author': 'Alan Storm', 'author_id': 4668, 'author_profile': 'https://Stackoverflow.com/users/4668', 'pm_score': 6, 'selected': False, 'text': '<p>Quick advice on best practices before I babble on about the magic <em>this</em> variable.  If you want Object-oriented programming (OOP) in Javascript that closely mirrors more traditional/classical inheritance patterns, pick a framework, learn its quirks, and don\'t try to get clever.  If you want to get clever, learn javascript as a functional language, and avoid thinking about things like classes.</p>\n\n<p>Which brings up one of the most important things to keep in mind about Javascript, and to repeat to yourself when it doesn\'t make sense.  Javascript does not have classes. If something looks like a class, it\'s a clever trick. Javascript has <strong>objects</strong> (no derisive quotes needed) and <strong>functions</strong>.  (that\'s not 100% accurate, functions are just objects, but it can sometimes be helpful to think of them as separate things)</p>\n\n<p>The <em>this</em> variable is attached to functions.  Whenever you invoke a function, <em>this</em> is given a certain value, depending on how you invoke the function.  This is often called the invocation pattern.</p>\n\n<p>There are four ways to invoke functions in javascript.  You can invoke the function as a <em>method</em>, as a <em>function</em>, as a <em>constructor</em>, and with <em>apply</em>.</p>\n\n<h2>As a Method</h2>\n\n<p>A method is a function that\'s attached to an object</p>\n\n<pre><code>var foo = {};\nfoo.someMethod = function(){\n    alert(this);\n}\n</code></pre>\n\n<p>When invoked as a method, <em>this</em> will be bound to the object the function/method is a part of.  In this example, this will be bound to foo.</p>\n\n<h2>As A Function</h2>\n\n<p>If you have a stand alone function, the <em>this</em> variable will be bound to the "global" object, almost always the <em>window</em> object in the context of a browser.</p>\n\n<pre><code> var foo = function(){\n    alert(this);\n }\n foo();\n</code></pre>\n\n<p><strong>This may be what\'s tripping you up</strong>, but don\'t feel bad.  Many people consider this a bad design decision.  Since a callback is invoked as a function and not as a method,  that\'s why you\'re seeing what appears to be inconsistent behaviour.</p>\n\n<p>Many people get around the problem by doing something like, um, this</p>\n\n<pre><code>var foo = {};\nfoo.someMethod = function (){\n    var that=this;\n    function bar(){\n        alert(that);\n    }\n}\n</code></pre>\n\n<p>You define a variable <em>that</em> which points to <em>this</em>. Closure (a topic all it\'s own) keeps <code>that</code> around, so if you call bar as a callback, it still has a reference.</p>\n\n<h2>As a Constructor</h2>\n\n<p>You can also invoke a function as a constructor.  Based on the naming convention you\'re using (<code>TestObject</code>) this also <strong>may be what you\'re doing and is what\'s tripping you up</strong>.</p>\n\n<p>You invoke a function as a Constructor with the <code>new</code> keyword.</p>\n\n<pre><code>function Foo(){\n    this.confusing = \'hell yeah\';\n}\nvar myObject = new Foo();\n</code></pre>\n\n<p>When invoked as a constructor, a new Object will be created, and <em>this</em> will be bound to that object.  Again, if you have inner functions and they\'re used as callbacks, you\'ll be invoking them as functions, and <em>this</em> will be bound to the global object.  Use that <code>var that = this;</code> trick/pattern.</p>\n\n<p>Some people think the constructor/new keyword was a bone thrown to Java/traditional OOP programmers as a way to create something similar to classes.</p>\n\n<h2>With the Apply Method.</h2>\n\n<p>Finally, every function has a method (yes, functions are objects in Javascript) named <code>apply</code>.  Apply lets you determine what the value of <em>this</em> will be, and also lets you pass in an array of arguments.  Here\'s a useless example.</p>\n\n<pre><code>function foo(a,b){\n    alert(a);\n    alert(b);\n    alert(this);\n}\nvar args = [\'ah\',\'be\'];\nfoo.apply(\'omg\',args);\n</code></pre>\n'}, {'answer_id': 81646, 'author': 'ujh', 'author_id': 4936, 'author_profile': 'https://Stackoverflow.com/users/4936', 'pm_score': 0, 'selected': False, 'text': '<p>If you\'re using Prototype you can use <a href="http://www.prototypejs.org/api/function/bind" rel="nofollow noreferrer">bind()</a> and <a href="http://www.prototypejs.org/api/function/bindAsEventListener" rel="nofollow noreferrer">bindAsEventListener()</a> to get around that problem.</p>\n'}, {'answer_id': 83730, 'author': 'Chase Seibert', 'author_id': 7679, 'author_profile': 'https://Stackoverflow.com/users/7679', 'pm_score': 1, 'selected': False, 'text': '<p>If you\'re using a javascript framework, there may be a handy method for dealing with this. In Prototype, for example, you can call a method and scope it to a particular "this" object:</p>\n\n<pre><code>var myObject = new TestObject();\nmyObject.firstMethod.bind(myObject);\n</code></pre>\n\n<p>Note: bind() returns a function, so you can also use it to pre-scope callbacks inside your class:</p>\n\n<pre><code>callBack.bind(this);\n</code></pre>\n\n<p><a href="http://www.prototypejs.org/api/function/bind" rel="nofollow noreferrer">http://www.prototypejs.org/api/function/bind</a></p>\n'}]
['https://Stackoverflow.com/questions/80084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']