多态参数 JavaScript



我正在尝试模仿jQuery animate()方法,为不受支持的浏览器(当然是Internet Explorer)去除opacity样式!

但是,我正在努力模仿 jQuery animate() 方法接受的参数。

根据jQuery文档:

.animate( properties [, duration] [, easing] [, complete] )
.animate( properties, options )

我想知道的是函数如何知道参数 2 是持续时间还是选项......?

请注意此处的三个参数:

$('#test').animate({opacity:0},200,function(){
    $(this).hide(); 
});

但我也可以像这样执行相同的函数(注意缓动参数):

$('#test').animate({opacity:0},200,'swing',function(){
    $(this).hide(); 
});

函数如何知道第三个参数是字符串,而不是函数?

当然不是这样做的????

if(typeof parameter1=='string'){
    // and so on
}

当然,这不是这样做的????

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() { }

我想知道的是函数如何知道参数 2 是持续时间还是选项......?

如果第二个参数是对象,则它是选项。如果可以解析为int,那就是duration。如果是函数,那就是callback,否则就是easing

最新更新