I've been catching up on JavaScript basics recently.
Here is a simple example to demonstrate the difference between the event target (where an event takes place), and the this reference (where an event handler is defined).
Consider the following hunk of HTML:
We could write an event handler like so:
Clicking on one of the list items will reveal that evtTarget references an LI element, while this references the DIV element. I like this style, but for various reasons we often wire event handlers like so:
And the script, which doesn't change a great deal:
Clicking in a list item will show us that the evtTarget is still an LI element, but this.nodeName will now show as undefined. The function List_onclick in the second example is part of the global object, which doesn't have a nodeName.
I always have to think about what this will reference in JavaScript, which is one reason the language makes me queasy.
Comments
I've written about how tricky "this" can be in the context of ASP.NET AJAX over on my weblog.
jason.diamond.name/weblog/2006/12/10/not-delegates
Somebody helped me out at the time with a link to an excellent document that I continue to look at from time to time that describes Closures - what makes all of this work (or not work :->) - in great detail.
http://jibbering.com/faq/faq_notes/closures.html