I saw the following defined in a function using jquery.
var $this = jQuery(this);
Is that not redundant? Both side of the equation are stating the same thing.
I saw the following defined in a function using jquery.
var $this = jQuery(this);
Is that not redundant? Both side of the equation are stating the same thing.
I think the $ in $this
is the confusing part here. Prefixing a variable with a $ is just convention to show that the variable is a jQuery object. That's all - it could have been called myElement
and it would be the same thing.
If part of the question is why you hold the variable in the first place, it's partly about efficiency and partly closures (keeping something in scope).
So, do this to avoid keep evaluating a DOM element into a jQuery object:
var $this = $("#container");
$this.addClass("highlight");
$this.focus(function() { alert("Got Focus!"); });
And to keep scope (due to closures):
var $this = $("container");
$("#send").click(function() {
//$this still in scope now
$this.addClass("highlight");
});
There are various uses for this. One common reason is to allow the defined variable to be captured in another function. For example, consider this:
var $this = jQuery(this);
$.get('/some/url', function (result) {
// do something with result
// and something with $this;
});
If this code were in, say, a click handler for an element then this
would of course refer to that element. However, in the AJAX callback the context for this
has been lost. By storing it in a variable, the function is able to capture the reference to that variable and retain the reference to the element which invoked the handler.
Two very good reasons:
Caching.
For performance reasons, if you're going to use $(this)
multiple times in a single block of code, it is good to store it into a variable once and use that instead. This avoids the program having to re-evaluate the same function call multiple times, which saves memory and processor power.
var $this = $(this);
$this.hide();
//...do something...
$this.show(); //doesn't need to evaluate $(this) again.
Loss of scope.
The variable name this
in Javascript has a special meaning. Often when using closure functions, the inner function will have it's own this
which means that you can't use the this
value from the outer function unless you store a copy of it in a separate variable that will retain scope. It is common on define a local variable named that
or self
or something similar to allow you to carry its scope through to the inner function. $this
could be used for the same purpose.
var $this = $(this);
$('.something').each(function() {
//in this function $(this) would be for the item being looped
//but $this was defined earlier, so still refers to the original object.
};