確かにこれはそのように行われていませんか????
if(typeof parameter1=='string'){
// and so on
}
はい、それはまさにそれが行われる方法です。
jQueryソースから:
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;
このように読みやすくするために書き直すことができます。
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;
アップデート
このロジックをより簡単に処理する方法が必要な場合は、candyが。と呼ばれるきちんとしたアレイヘルパーを提供しますpersuade
。この関数を使用すると、型のリストを含む配列(またはarguments
)オブジェクトを渡すことができます。タイプごとに整理された引数を持つ配列が返されます。これは、多態的なパラメータを処理する簡単な方法です。
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() { }