JavaScript: this and that.

This is a brief description of a technique recommend by Douglas Crockford, probably in Act III of his JavaScript video series.

Code that looks right, but is wrong:

clip_image002

There are a few workarounds; the one Douglas Crockford recommends is to create a new variable (conventionally named “that”) referenced by the inner function.

clip_image004

The “that” convention is fitting because you’re saying, “It’s not the close-by this, it’s that ‘this’ from over there.” Kinda cute.

Incidentally, CoffeeScript has a construct to compensate for the confusing (although very logical) behavior of this in JavaScript. I like CoffeeScript; been playing with it in a side project and hope to use it for a Javascript-heavy green-field project soon.

Bottom Line: with JavaScript, when you have a function defined inside of another function, “this” in the inner function might not be what you expect.

This entry was posted in JavaScript, Programming. Bookmark the permalink.
  • Confused, perplexed and somewhat dumbfounded; but finally getting the hang of it!

    • Jason Pettys

      Glad to hear that! Hope this article was some help in grokking “this” in JavaScript. It’s definitely an issue: both CoffeeScript and now TypeScript have constructs to help clear it up, and there is some discussion about cleaning it up in the next version of the JavaScript language itself.

      Thanks for reading!