Caching $ (this) in jQuery is best practice?

We all know that it is good to cache calls in the DOM, so instead of calling $ ('# someElement') for more time, just save it in var $ someElement and use this.

But the same when using $ (this) inside an event listener? Should $ (this) be cached?

Thanks.

+6
source share
3 answers

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 the function call to create the same object again

+5
source

If you call $(this) several times, it is better to do something like var $this = $(this);

+7
source

If you reference the same element later in the event function, yes. Outside of a function, this makes no sense, because the value of this will be changed.

+2
source

Source: https://habr.com/ru/post/910178/


All Articles