erichynds

Welcome to my online development portfolio and blog. I'm Eric Hynds, a 23 year old website developer living outside of Boston, Massachusetts, and I'm passionate about developing functional, standard-compliant, and user-friendly websites.

Archive for January, 2010

jQuery and Performance: What is ‘this’?

Monday, January 4th, 2010

In my opinion, one of the best jQuery performance tips is to minimize your use of jQuery. That is, find a balance between using jQuery and plain ol’ JavaScript, and a good place to start is with ‘this‘. Many developers use $(this) exclusively as their hammer inside callbacks and forget about this, but the difference is distinct:

When inside a jQuery method’s anonymous callback function, this is a reference to the current DOM element. $(this) turns this into a jQuery object and exposes jQuery’s methods. A jQuery object is nothing more than a beefed-up array of DOM elements.

Digging a little deeper

As you begin to nest functions the context of this changes:

<a href="#"><span>Hello World</span></a>
 
$("a").click(function(event){
	var self = this;
 
	$(this).find("span").each(function(){
		console.log(self, this);
	});
 
	event.preventDefault();
});

In this example I save this to the variable “self” so it can be referenced inside the each() loop. Otherwise it’s impossible to reference this as the anchor element inside the loop, because this is now the “span” DOM element.

Depending on what you’re doing, using this is sometimes easier and always faster than $(this). I’m not talking about scraping jQuery altogether, but rather recognizing that a lot of DOM interaction (especially the simple stuff) can just as easily be done in vanilla JS using this; you are not required to use the jQuery API. Example:

(more…)