Why does 'this' in a jquery chain chain call a DOM element?

Therefore, I know that when using $.fn.each , $.fn.bind , etc. the standard for the this in jQuery chained callbacks is the DOM element.

I know that in my development, at least I usually want the DOM element to be completed in a jQuery set - in 90% of the cases when I finished doing var $this = $(this) . I'm sure there was a good (probably performance-based) justification for why they decided to bind to the expanded item, but does anyone know what exactly it was?

This is one of those things that I feel when I know the answer to open the door to understanding the library and language at a deeper level.

+6
source share
2 answers

By forbidding anyone to point out John Resig’s article specifically addressing this issue, I doubt the final answer is being proposed. But I often asked this question when I started using jQuery and came to the conclusion that this is the least harmful thing. After all, it is entirely possible that all you need is a DOM element. If you need / need to use the jQuery wrapper, then $() is only three keystrokes (or moreover you do var $this = $(this); thing). In contrast to the fact that the library always does this for you, which is associated with several function calls and memory allocation, when it may well be that you do not need it.

For example, consider:

 $("input").each(function() { // Use this.value }); 

There is no reason for wrapping jQuery around a DOM element. this.value is all you need for all input fields (except input type="file" , but val() won't help you either). In event handlers (where this also a β€œjust” source element), you may not look at this at all.

But in this case:

 $(":input").each(function() { var val = $(this).val(); // Use `val` }); 

... there is a genuine reason to use $(this) : Selector :input corresponds to several different types of elements ( input , select , button , textarea ), for which the value comes from different properties and val() theses that are for you.

So, I came to the conclusion that providing a raw element is performance. If you do not use it at all or use only the basic DOM properties, there is no need to wrap it in a jQuery instance. If you need / need to do this, you can do it in your code.

+2
source

I'm sure there was a good (probably performance-based) justification

I am sure that it is so. If there is a possibility that you may not need a jQuery wrapper (which is - it is unlikely that you rarely have to work directly with DOM properties, especially in callbacks to functions like val , indeed, you may not need to look at the element at all), then Waste time and processing resources when creating a jQuery object.

As an example, here is jsperf , which shows that executing $(this) for each element of the loop contains as much overhead as each does.

+2
source

Source: https://habr.com/ru/post/905480/


All Articles