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.
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.
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.
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