I often see the code like this one:
$('.element').on('click', function(event) {
var element = this;
// somecode that uses "element"
});
Is there any reason to cache this
?
I often see the code like this one:
$('.element').on('click', function(event) {
var element = this;
// somecode that uses "element"
});
Is there any reason to cache this
?
This is necessary if the code contains a closure that needs to access this
. this
is not a local variable, so it will not be captured in the closure, you need to bind a local variable for that purpose.
You also need it if the code contains a loop using a function like $.each()
, and the body of the loop needs to refer to the element. These functions rebind this
in the body to the current iteration object.
A lot of people set a reference to this
if they need to reference it in another scope of code. For example:
$('.element').on('click', function(event) {
var element = this;
// somecode that users "element"
function foo() {
//$(this).text() WONT Work!
alert($(element).text()); //references the element that was clicked
}
});
Once you are inside a function or loop, this
might refer to an object within that function. Therefor explicity assigning the element allows you to always access it, independent of the scope.
this
is not a jQuery element, wrap it in $(this)
.
Caching is good because it stores the element, and it doesn't take up memory or processing time trying to re-find the element. However, this
changes on scope so you might not want to cache that one.