Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

On the page 109 of the book "Learning JavaScript Design Patterns", there is a code sample which 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 like this:

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

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

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

Now I understand. I wish the author of the book "Learning JavaScript Design Patterns" could add this comment too, when he cited this code sample.

like image 428
user1481096 Avatar asked Jul 17 '13 12:07

user1481096


2 Answers

jQuery([1]) is simply passing an array with one entry that contains the integer 1 into jQuery, that would return a wrapper to that array containing all jQuery prototype methods.

It later assigns the element argument variable into the very same array and then returns the entire jQuery instance.

From the looks of it, the whole function simply injects a single element into a re-used jQuery object and returns it.

It is presumed to speed things up and it actually does when you count millions of iterations over a second, but in my opinion this is a clear case of micro-optimization that can bite you in the ass during long debug hours. — Perfection Kills.

like image 78
David Hellsing Avatar answered Nov 15 '22 08:11

David Hellsing


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

You can also write it like -

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

I think the reason they do this so there isn't any confusion on how many elements will be in the array.

like image 23
ddavison Avatar answered Nov 15 '22 10:11

ddavison