Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'this' in jquery chaining callbacks a DOM element?

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.

like image 570
George Mauer Avatar asked Jan 09 '12 00:01

George Mauer


People also ask

What is callback in jQuery?

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.

What is true about jQuery method chaining?

With jQuery, you can chain together actions/methods. Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.

What is called chaining in jQuery?

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.

What is this keyword in jQuery?

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.


1 Answers

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.

like image 60
lonesomeday Avatar answered Nov 15 '22 04:11

lonesomeday