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.