Stephen
Stephen

Reputation:

Why use extend in JQuery/JavaScript?

In the following JQuery UI widget the author has used extend to include two more functions in $.ui.autocomplete, why? Is this a JQuery specific pattern or is it something I could be considering 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

Upvotes: 4

Views: 2805

Answers (2)

Moncader
Moncader

Reputation: 3388

There is no reason to use it and in reality it will be slower than doing it the manual regular JS way. Often jQuery developers have a problem in that they only know how to use jQuery and not regular javascript. jQuery's extend function is a recursive actually quite slow beast compared to managing things yourself.

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

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

First of all, let's look at what is necessary to do the non-jQuery extend way.

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

On line 315 we see a quick little test to organize arguments a bit. Next we have another little IF statement with possible code execution. Next is another IF with a function call inside of the if. Next is another IF. We then enter a FOR loop for each of the arguments, in our case two rounds. On each pass first there is a check for null values, needless in our situation since we made the functions ourselves. Now we have a FOR IN loop which by nature is very slow due to having to look up each of the items inside the object map instead of just iterating over an iterator. Now we finally copy one of our functions in to jQuery! Do another check to make sure we don't enter an infinite loop... For our case this time we just do one more little IF check. And the loop repeats until things are done.

Therefore this method is far slower than directly copying in to the jQuery object itself. A common problem for people that use API's is that even though the function usage might be simple and look fast and easy, the internals can be very complex and slow compared to doing things yourself.

Upvotes: 10

Ruan Mendes
Ruan Mendes

Reputation: 92274

In this case, the only benefit I see is that you don't need to type $.ui.autocomplete twice, once for each function declaration.

Upvotes: 2

Related Questions