Friday, June 17, 2011

Beginner JavaScript Trick

So this trick is probably old-hat for any experienced JavaScript programmer, but the problem it solves tripped me up when I first started using JavaScript in depth. I was maintaining code written by another developer and at the beginning of every JavaScript module he wrote he would always have the following line:

var that = this;


I didn't really understand the point of it at the time until I later ran into a frustrating bug where this wasn't pointing to the (top-level) object I thought it should. Sure enough, it was because I was referring to this within an event handler and this was pointing to the target of the event rather than the top-level object. The light bulb went off in my head. So whenever you want to refer to your top-level object, you can just reference that and use this everywhere else. This article provides a good explanation of the issue.

Sometime later, I was watching Douglas Crockford's JavaScript lectures on Yahoo and saw that he uses the same technique. Unfortunately, those videos are no longer available on Yahoo.

No comments: