6

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.

Francisc
  • 77,430
  • 63
  • 180
  • 276

3 Answers3

7

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

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Is there performance gain or is it just for saving characters (2 per usage)? – Tx3 Mar 07 '12 at 14:34
  • @Tx3 No, it is not just for saving characters, it is saving function calls. You did function call every time when you do `$(this)`. – xdazz Mar 07 '12 at 14:36
  • sure, I was just thinking what kind of operation it is doing when it does the "wrapping". Anyway, I have been using it like you suggested, so it was just curiosity. – Tx3 Mar 07 '12 at 14:42
7

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

charlietfl
  • 170,828
  • 13
  • 121
  • 150
2

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.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176