Why use extension in jQuery / javascript?

In the next jQuery UI widget, the author used the extension to include two more functions in $.ui.autocomplete , why? Is this a specific jQuery template or is it something I can consider in plain JS?

 $.extend( $.ui.autocomplete, { escapeRegex: function( value ) { return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }, filter: function(array, term) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" ); return $.grep( array, function(value) { return matcher.test( value.label || value.value || value ); }); } }); 

https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.autocomplete.js#L385

+4
source share
2 answers

There is no reason to use it, and in fact it will be slower than executing the manual regular JS method. Often jQuery developers have a problem in that they only know how to use jQuery and not regular javascript. The jQuery extension function is a recursive, actually rather slow beast, compared to the controls themselves.

* edit * Since people do not want to accept this answer, let me show why there is no reason.

If you look at jQuery code on github here: https://github.com/jquery/jquery/blob/master/src/core.js , you will find the jQuery.extend definition on line 313.

First of all, let's see what needs to be done to extend non-jQuery.

 $.ui.autocomplete.escapeRegex = function() {} $.ui.autocomplete.filter = function() {} 

Two definitions, no function calls. Very simple and fast code.

This is what jQuery does if you use the extension.

On line 315 we will see a quick little test for organizing the arguments. Then we have another small IF statement with possible code execution. Next is another IF with a function call inside if. Next is another IF. Then we introduce a FOR loop for each of the arguments, in our case two rounds. On each pass, first, a check of zero values ​​that are unnecessary in our situation is performed, since we ourselves performed these functions. Now we have a FOR IN loop, which by its nature is very slow due to the need to search for each element inside the map of objects, and not just iterate through an iterator. Now we finally copy one of our functions in jQuery! Do one more check to make sure that we are not introducing an infinite loop ... For our case, this time we just do one more small IF check. And the cycle repeats until everything is completed.

Therefore, this method is far slower than copying directly to a jQuery object. A common problem for users using the API is that even if using functions can be simple and quick and easy, the internal environment can be very complex and slow compared to what you do yourself.

+10
source

In this case, the only thing I see is that you do not need to enter $ .ui.autocomplete twice, once for each function declaration.

+2
source

All Articles