Reputation: 80505
We all know it's good to cache calls to the DOM, so instead of calling $('#someElement') more times, just save it to a var $someElement and use that.
But is it the same when using $(this) inside an event listener for example? Should $(this) be cached?
Thank you.
Upvotes: 6
Views: 1000
Reputation: 171698
Each time you call $(this)
or $(selector)
it is a function call to create a new jQuery object... so if you have already created it once, caching will save calling a function to create the same object again
Upvotes: 7
Reputation: 160973
If you call $(this)
multiple times, it is better to do something like var $this = $(this);
Upvotes: 7
Reputation: 114447
If you refer to the same element later in the event function, yes. Outside of the function it doesn't make any sense to do so because the value of this
will have changed.
Upvotes: 2