Surely this is not done like so????
if(typeof parameter1=='string'){
// and so on
}
Yes, that is exactly how it is done.
From the jQuery source:
var opt = speed && typeof speed === "object" ? jQuery.extend({},
speed) : {
complete: fn || !fn && easing || jQuery.isFunction(speed) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
Can be rewritten to be more readable this way:
var opt = { };
if (typeof speed == 'object')
opt = jQuery.extend({ }, speed);
else {
if (fn)
opt.complete = fn;
else if (easing)
opt.complete = easing;
else if (jQuery.isFunction(speed))
opt.complete = speed;
opt.duration = speed;
if (fn && easing)
opt.easing = easing;
else if (easing && !jQuery.isFunction(easing))
opt.easing = easing;
}
if (jQuery.fx.off)
opt.duration = 0;
else if (typeof opt.duration === 'number')
opt.duration = opt.duration;
else if (opt.duration in jQuery.fx.speeds)
opt.duration = jQuery.fx.speeds[opt.duration];
else
opt.duration = jQuery.fx.speeds._default;
Update
If you want an easier way to take care of this logic for you, candy provides a neat Array helper called persuade
. This function allows you to pass in an array (or arguments
) object with a list of types. You will be returned an array with the arguments organized by the types. It's an easy way to deal with polymorphic parameters:
function foo(/* duration, easing, complete */) {
var args = candy.Arrays.persuade(arguments, [ 'number', 'string', 'function' ]);
var duration = args[0], easing = args[1], complete = args[2];
console.log(duration, easing, complete);
}
foo('test');
// => undefined, 'test', undefined
foo(2, function() { });
// => 2, undefined, function() { }