
Finally someone makes sense of JavaScript's this keyword - legomatic
http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/
======
statictype
I used to always run into trouble when trying to use 'this' inside a closure
defined within an object's method.

Now, I just put

    
    
        var that = this;
    

at the top of very method and use 'that' everywhere in the function.

~~~
jrockway
Aha! I also do "var self = this;" but feel really bad about it, like I'm
missing something obvious about the language. I guess I'm not.

~~~
msy
You're not alone, every time I do this I feel like I'm going wrong somewhere.
I know it's avoidable via binding/currying/proxying but often those solutions
end up looking uglier and are harder to follow.

------
jessedhillon
Douglas Crockford has said that he considers Lisp and Javascript to be similar
languages. For that reason, I think it would help those confused/frustrated
with 'this' to read the chapters of SICP that relate to the environment model,
and to 'eval' and 'apply':

Environment model of evaluation, [http://mitpress.mit.edu/sicp/full-
text/book/book-Z-H-21.html...](http://mitpress.mit.edu/sicp/full-
text/book/book-Z-H-21.html#%_sec_3.2)

Metacircular evaluator, [http://mitpress.mit.edu/sicp/full-text/book/book-
Z-H-26.html...](http://mitpress.mit.edu/sicp/full-text/book/book-
Z-H-26.html#%_sec_4.1)

The environment model is crucially helpful. Applying it to Javascript, think
of bound functions (ones which are methods on instantiated objects) implicitly
having a 'let this = instance' statement prepended to their bodies.

~~~
jhuni
JavaScript is incredibly different from Lisp, at least syntactically. Here are
some legal JavaScript expressions:

    
    
      ++x+x++
      x >> 6 > y >> 6
      5 % 2 / 5 * 5 + 1

~~~
sid0
It's good that Crockford meant semantically, then.

------
djacobs
Douglas Crockford does a good job of explaining this in _JavaScript: The Good
Parts_. That book comes highly recommended.

------
gruseom
I simply made a pact with myself never to understand that monstrosity and so
never to use it (except when forced to, e.g. by some library). My voyages in
Javascript have been delightful ever since.

~~~
geuis
But in a manner of speaking, isn't your statement similar to a C++ programmer
preferring to avoid understanding pointers?

I found this article to be a little dense if a less experienced js dev is
trying to read it. That being said, if you _really_ want to understand
javascript as a language you have to understand "this".

I recommend starting with the 5 examples of how "this" gets assigned. Keep
reading those until you understand what they are saying. Then go back and read
the entire article again, perhaps a couple of times.

I promise that once it sinks in, you'll be a better javascript programmer.

~~~
gruseom
As Wittgenstein once said (and please, if anyone knows where, I've been trying
to find it again for years): You can't have a clear picture of a stormy sea.
"This" is an ill-defined concept (illustrated by the 3 categories and 5
subcategories of the OP) which, from what I've seen, often leads to
unnecessary complexity.

What really convinces me not to use it is that I can easily write my programs
without it and they come out better. Specifically, they come out with less
coupling.

Is that like pointers? No, pointers are not an ill-defined concept. People get
into trouble with pointers because they're a sharp tool. Some sharp tools are
nevertheless indispensable, as pointers are to C. Javascript's _this_ is not a
sharp tool, it's a hodgepodge.

Pointers take you closer to the machine. That can be useful, especially for
efficiency. What does JS _this_ take you closer to? A complicated evaluation
model that has nothing intrinsically to do with anything other than itself.
Since its cost is high (in complexity) and its benefit zero (relative to other
ways of writing JS), why invest in it? There is a no-brainer here: in exchange
for expending less effort, I get simpler programs. Meanwhile I can work at
understanding other things that are beautiful and/or useful.

~~~
M1573RMU74710N
> "This" is an ill-defined concept (illustrated by the 3 categories and 5
> subcategories of the OP)

I would disagree with that.

The concept behind "this" is actually pretty simple and well-defined: it's
part of the execution context that every function has in Javascript...and it's
behavior is predictable based on a small set of principles outlined in the OP.

What those various examples demonstrate is that it's a __dynamic __concept (an
important distinction imho). It's this property which gives a lot of novice
developers trouble, but it's also what makes it extremely powerful.

The "effort" you speak of is the extremely minor effort of remembering how
"this" behaves in a given scenario (which again, is basically one of several
well-defined possibilities).....as opposed to the effort of coding "around"
using "this" which will add just as much complexity to your code overall.

To me your suggestion sounds like saying you should only buy what you can pay
for with exact change because it's too much "effort" to do some simple
arithmetic each time to determine if you've received the correct change.

That's true of course, but this also hinders you in what you can do, and
requires effort itself.

I would say both strategies have their benefits and drawbacks, but are
ultimately comparable. You can certainly code "around" the this keyword; for
example by using closures to create custom types instead of a constructor...

IMHO, avoiding either strategy is the wrong way to go. What you should do is
evaluate each situation and determine which strategy offers the best
combination of benefits and drawbacks.

In my example, using a closure might be more expressive in some ways, etc
etc... but it consumes more memory, will break the instanceof operator, etc
etc. There's always trade-offs.

It may be that most of your JS code doesn't require the use of "this", but if
a programmer is not able to understand it and use it effectively when the
situation calls for it, they will never be complete as a JS coder.

~~~
gruseom
Of course I can use it if "the situation calls for it". But that's almost
never the case.

"This" causes hidden coupling. The difficulty isn't remembering how "this"
works (that's an annoyance), it's figuring out how a program that uses it
heavily works when all the action-at-a-distance kicks in.

There is no intrinsic value in being "complete as a JS coder". JS isn't
scripture.

------
stewbrew
Quite frankly, I personally fail to see the sense of this.

Interesting read though.

------
mdpm
dear coffeescript,

thank you for =>

~~~
zmanji
The fat arrow is the best piece of syntactic sugar cs offers.

~~~
DanielRibeiro
I like the _class_ and _for comprehensions_ sugar very much as well.

~~~
necubi
My favorite is the Maybe-monad-esque ? syntax. It lets you write expressions
like this: obj.a?.b?.c?() which will execute normally if all those properties
exist, but return null instead of failing if they don't.

------
pom
I had trouble with this at first, but an easy thing to remember is that "this"
is scoped dynamically; as many have noted before, you can easily create a
lexical "that" or "self" reference from it, but the other way around is
impossible. This dynamic scope is a bit strange when everything else has local
scope but it can be quite powerful.

When "this" gives you a hard time, the Function.bind() method is often a good
solution too.

------
chug2k
[http://justin.harmonize.fm/index.php/2009/09/an-
introduction...](http://justin.harmonize.fm/index.php/2009/09/an-introduction-
to-javascripts-this/) is another great article

------
Breefield
I now feel fortunate to have started out with Actionscript 2. If there's
anything that language drives home it's "this," due to the fact that you're
usually writing code specific to an instance object on the stage. So the
concept of var self = this; makes too much sense.

------
nitrogen
What is the benefit to having 'this' defined based on where a function is
executed rather than where it is created? Is this mainly an artifact of the
ability to assign a function created in one place to an object created
elsewhere?

~~~
munificent
It allows you to inherit functions from a prototype and still have them
execute against the current receiver. Consider:

    
    
        var base = {
          greet: function() { log('my name is ' + this.name); },
          name: 'base'
        }
    
        var derived {
          __proto__: base,
          name: 'derived'
        }
    
        derived.greet();
    

If the greet function was bound at creation time to base, then the last line
would print "my name is base" instead of the desired "my name is derived".

------
d_r
I also found JavaScript Garden (posted on HN a few weeks ago) incredibly
useful in un-confusing my understanding of JS.

<http://bonsaiden.github.com/JavaScript-Garden/>

------
discopalevo
nothing about context, then function called in expressions

var a = { b:function(){...}}; a.b() // a var c = false; (c || a.b)() // window

this context is always global

~~~
sesqu
That's a needlessly complicated example. You could just write
(function(){alert(this)})() -- and in fact, that's what was the very first
example.

------
tocomment
I still don't get it :-(

------
aneth
Sense could be an overstatement.

------
hackermom
For the pragmatics, a simpler and not so cluttered example of the constructor,
illustrating what 'this' does and how you can pass 'this' by argument:

    
    
      function value()
      {
          this.v = 32;
      }
    
      function twice( n )
      {
          n.v += n.v;
      }
    
      number = new value();
      document.write( number.v + ' ' );
    
      twice( number );
      document.write( number.v );

------
kwamenum86
duh.

