Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the rationale for the behavior of the 'this' keyword in JavaScript?
    text
    copied!<p>I am asking this from a language design point of view. So I am trying to find out</p> <ol> <li>What is the rationale for the behavior of <code>this</code>?</li> <li>To what degree the behavior of <code>this</code> was a mistake, or could be improved upon?</li> </ol> <hr> <p>To clarify why I'm uneasy about <code>this</code>, consider this example:</p> <pre><code>var a = {}; a.f = function(){ return this; } var f = a.f; // f() != a.f() </code></pre> <p>Note how easily the object to which <code>f()</code> belong is lost: separated from <code>a</code>, <code>this</code> becomes the global object (<code>window</code> for browsers). </p> <p>Now consider:</p> <pre><code>var newA = function(){ var self = {}; self.f = function(){ return self; } return self; } var a = newA(); var f = a.f; // f() == a.f() ! </code></pre> <p>Without using <code>this</code> at all, we are able to establish and maintain the object context regardless of where or how the method is used. I can't help but think that, with the power that closures provide, <code>this</code> becomes superfluous, and perhaps even a little dangerous...</p> <p>I'm not on some vendetta against <code>this</code>, or looking to start an argument; I'm merely trying to better understand it. I do appreciate that 'this' can be useful, but recognize that <a href="http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/c95c2d8eb232e466#dad2785d7263e699" rel="nofollow noreferrer">it can be confusing</a> as well... Certainly confusing to beginners, and perhaps to experts as well in sufficiently obscure cases.</p> <p>And yet, it remains a heavily-used and seemingly well-respected part of the language, in a time when other core aspects of the language seem fair game for shunning (i.e., Crockford and <code>with</code> or <code>new</code>). What am I missing then, that makes <code>this</code> indispensable?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload