What does the jquery operator "var collection = jQuery ([1]); mean?

There is sample code on page 109 of the Learning JavaScript Design Patterns book that confused me.

jQuery.single = (function( o ){ var collection = jQuery([1]); // <-- i want to ask this line return function( element) { // give collection the element collection[0] = element; // return the collection return collection; } })(); 

The use of the function is as follows:

 $('div').on('click', function() { var html = jQuery.single( this ).next().html(); console.log( html ); }); 

Update: Thanks for the answer. I checked the source code from the author page 76 bytes for faster jQuery

 var collection = jQuery([1]); // Fill with 1 item, to make sure length === 1 

Now I got it. I would like the author of Learning JavaScript Design Patterns to also add this comment when he quotes this sample code.

+6
source share
2 answers

jQuery([1]) simply passes an array with one record containing the integer 1 in jQuery, which returns a wrapper in this array containing all the jQuery prototype methods.

It then assigns the variable of the element argument to the same array, and then returns the entire jQuery instance.

In appearance, the entire function simply inserts a single element into a reused jQuery object and returns it.

It is assumed that the speed is accelerated, and in fact this happens when you count millions of iterations for more than a second, but, in my opinion, this is a clear example of micro-optimization that can bite your ass for long debugging hours. - Perfection kills.

+6
source

You are passing a predefined array to the jQuery () function. let [1] mean "a new array with only one element"

You can also write it as -

 var collection = jQuery(new Array(1)); // or even $(new Array(1)); 

I think they do this, so there is no confusion about how many elements will be in the array.

+1
source

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


All Articles