Overloading

Allows function overloading using argument switching.

jQuery uses overloading. A good example is the top-level jQuery method itself which performs argument switching and is therefore overloaded.



Overview


Many languages support function overloading which is a feature that allows you to have multiple functions with the same name, but they all have a different set of parameters. For example add(x, y) and add(x, y, z) are overloaded functions. In typed languages the parameter type is also significant. We may have add(x, y) which adds two numbers and add(s, t) which concatenating two string values with s and t of type string.

JavaScript does not support overloading. However, you mimic it with a technique called argument switching. jQuery uses it extensively. In fact, the main jQuery method itself (which is aliased as $) is overloaded. It does different things depending on the arguments that are being passed. Here are some examples of different uses for jQuery (or $):

$(function() {
   // ... 
});

This is a shorthand for $(document).ready() which runs when the DOM has been fully loaded. A function is passed into the $() function.

Here is another example:

$("#menu").addClass("active");

This is the regular selector syntax which returns a list of elements that meet the selector criteria. The $() function is passed a string.

And another example:

$("<p>Hello there!</p>").insertAfter("#intro");

This inserts a new DOM element after a specific location in the HTML document.

These are all examples of function overloading. The overloaded versions expect argument types that are either a function or a string. As you would expect the jQuery source code checks for the selector type. Here is an outline of this code (simplified):

init: function( selector, context, rootjQuery ) {

        // HANDLE: $(HTML)
        if (....) {

           return this;
        }

        // HANDLE: $(expr) 
        if (....) {

           return this;
        }

        // HANDLE: $(function)
        if ( jQuery.isFunction( selector ) ) {
           return rootjQuery.ready( selector );
        }
        // ...
}

Interestingly, this goes beyond standard function overloading. If the selector type is a string value, the function needs to determine whether this is a CSS selector or an HTML string. This could be called semantic overloading.