jQuery in Action
The jQuery plugin authoring guidelines
191
Using this pattern, optional parameters are gathered into a single parameter
in the guise of a JavaScript
Object
instance whose property name/value pairs
serve as the optional parameters.
Using this technique, our first example could be written as
complex(valueA, {p7: valueB});
And the second as the following:
complex(valueA, {
p3: valueC,
p4: valueD,
p7: valueB
});
Much better!
We don't have to account for omitted parameters with placeholder nulls, and
we also don't need to count parameters; each optional parameter is conveniently
labeled so that it's clear to see exactly what it represents (when we use better
parameter names than
labeled so that it's clear to see exactly what it represents (when we use better
parameter names than
p1
through
p7
, that is).
Although this is obviously a great advantage to the caller of our complex func-
tions, what about the ramifications for us as the function authors? As it turns out,
we've already seen a jQuery-supplied mechanism that makes it easy for us to
gather these optional parameters together and to merge them with default val-
ues. Let's reconsider our complex example function with a required parameter
and six options. The new, simplified signature is
we've already seen a jQuery-supplied mechanism that makes it easy for us to
gather these optional parameters together and to merge them with default val-
ues. Let's reconsider our complex example function with a required parameter
and six options. The new, simplified signature is
complex(p1,options)
Within our function, we can merge those options with default values with the
handy
handy
$.extend()
utility function. Consider the following:
function complex(p1,options) {
var settings = $.extend({
option1: defaultValue1,
option2: defaultValue2,
option3: defaultValue3,
option4: defaultValue4,
option5: defaultValue5,
option6: defaultValue6
},options||{});
// remainder of function...
}
By merging the values passed to us by the page author in the
options
parameter
with an object containing all the available options with their default values, the