JavaScript Function Invocation and “this”

Understanding JavaScript Function Invocation and “this” aims to clear up some of the misunderstanding around the semantics of ‘this’ in JavaScript function invocations.

If you use jQuery, then you should read the three paragraphs titled ‘On jQuery’, even if you don’t read anything else on the page:

Because jQuery makes such heavy use of anonymous callback functions, it uses the call method internally to set the this value of those callbacks to a more useful value. For instance, instead of receiving window as this in all event handlers (as you would without special intervention), jQuery invokes call on the callback with the element that set up the event handler as its first parameter.

 

This is extremely useful, because the default value of this in anonymous callbacks is not particularly useful, but it can give beginners to JavaScript the impression that this is, in general a strange, often mutated concept that is hard to reason about.

If you work with jQuery a lot then it can be easy to blur the lines between jQuery and JavaScript syntax, so understanding that jQuery is making internal assignments of ‘this’ to help you is a useful thing to know.

Tags: ,

Posted on Saturday, October 15, 2011 4:51 PM |

Like this? Share it!

No comments posted yet.

Post a comment
Please add 2 and 3 and type the answer here:
Remember me?
Ensure the word in this box says 'orange':