I ran across some code at work as follows:
var $divs = $('div');
var $jq = $([1]);
$divs.each(function () {
$jq.context = $jq[0] = this;
// ... do stuff ...
});
I perf'd the above, and it seems much faster than having $this = $(this);
at the top of the function. Inside the function, the $jq
variable has a standard assortment of typical jQuery methods called off of it (.hasClass(), .data(), .find(), ...
), and the code works as intended.
I'm wondering what the tradeoffs here are; i.e. what do you lose by not constructing a new object each time? Am I just losing the "history" (i.e. .pushStack(), .end(), .andSelf(), ...
)? Should I be doing this all of the time?
Also, is this a named pattern? I couldn't for the life of me figure out how to research this on Google.