Options Hash

Reduces multiple function arguments to a single argument.

jQuery greatly simplifies its API by using Options Hash arguments.



Overview


The Options Hash reduces the number of parameters in a function by grouping several into a single parameter object with a set of name/value pairs. The general usage pattern is like this:

var thing = new Thing(parm1, parm2, {
                       option1: "val1", 
                       option2, "val2", 
                       option3, "val3" }); 

The last argument is an object with 3 name/value pairs. Perhaps this last argument accepts, say, 10 different name/value pairs, but when not provided the Thing constructor function will assign default values for the 7 that are missing.

A great example of the Options Hash in jQuery is the Ajax method. Here is the method's description from the jQuery website:

jQuery.Ajax(url, [settings]);
----------------------------------------------------------------------
url: A string containing the url to which the request is sent.
settings: A set of key/value pairs that configure the Ajax request. All settings are optional.

The optional setting parameter is exactly the Options Hash idiom as we know it: it is used as a configuration parameter and all items are optional (there are about a dozen or so possible items in jQuery's settings object).



Chaining