0

Say I have an event handler bound to an element, e.g.

$('#mybutton').click(function() {
    // CODE
});

And I want to do multiple operations on the clicked element (or, really, any element set) inside the handler.

For CODE I could do:

$(this).something();
$(this).somethingElse();

or:

var abc = $(this);
abc.something();
abc.somethingElse();

(assume there's a reason to not chain the calls, eg. a conditional statement on somethingElse, omitted here for brevity)

When is it preferable to use the var?
Certainly it's faster to not run the selector multiple times, but I'm asking about coding style rather than functional efficiency.

dlchambers
  • 3,511
  • 3
  • 29
  • 34

1 Answers1

1

Personally for me, if you use something more than once it should be placed into a variable. It looks better and is easier to read.

Glen
  • 344
  • 1
  • 14