So I know that when using $.fn.each
, $.fn.bind
, etc, it is standard for the this
keyword within jQuery chaining callbacks to be a DOM element.
I know in my development at least I usually want the DOM element wrapped in a jQuery set - 90% of the time I end up doing var $this = $(this)
. I am sure there was a good (likely performance-based) rationale for why they chose to bind to the unwrapped element but does anyone know what exactly it was?
This is one of those things that I feel like knowing the answer to might open the door for understanding the library and language at a deeper level.
jQuery Callback Functions JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors. To prevent this, you can create a callback function. A callback function is executed after the current effect is finished.
With jQuery, you can chain together actions/methods. Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.
jQuery | chaining() With jQuery, we can use do chaining which means to chain together multiple methods in a single statement on a single element. We have been using a single statement at once, but now using the chaining method we can bind multiple methods to make the code short.
The this Keyword is a reference to DOM elements of invocation. We can call all DOM methods on it. $() is a jQuery constructor and in $(this), we are just passing this as a parameter so that we can use the jQuery function and methods.
I am sure there was a good (likely performance-based) rationale
I'm sure this is precisely it. If there's any likelihood that you might not need the jQuery wrapper (which there is – it's hardly uncommon to work directly on DOM properties, especially in callbacks to functions like val
; indeed, you might not need to look at the element at all) then you don't want to waste time and processing resources in creating the jQuery object.
As an example, here's a jsperf that shows that doing $(this)
on every element in the loop carries about as much overhead as the each
function does itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With