2012-10-05 36 views
3

我刚刚玩了一下animate()方法。jQuery方法,可选参数的顺序

.animate(属性[,时间] [,缓和] [,完整])

我知道,我没有给所有的参数传递给在javascript函数。但我想知道的是,如何jquery算出function(){ }引用回调函数,它实际上是第4个参数,而不是缓动字符串(它是3:rd)?

$('div').animate({ height: '10px' }, 100, function(){ }); 
+0

这种事情通常是通过检查参数的类型来实现。 – MyStream

回答

3

有简单的测试来检查类型:

the source codeanimate电话speed):

jQuery.speed = function(speed, easing, fn) { 
    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 
    }; 

... 

isFunction: function(obj) { 
     return jQuery.type(obj) === "function"; 
    }, 

... 

type: function(obj) { 
     return obj == null ? 
      String(obj) : 
      class2type[ core_toString.call(obj) ] || "object"; 
    }, 

... 

core_toString = Object.prototype.toString 

... 

jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { 
    class2type[ "[object " + name + "]" ] = name.toLowerCase(); 
}); 

所以基本上它会检查Object.prototype.toString.call(fn)"[object Function]"

1

JQuery的着眼于参数的型发现的那样,缓解参数的类型为字符串,而完整参数是型功能的。

查看.animate()的API查找每个参数的类型。

实施例:

function test(first, second, third) { 
    if (typeof third == 'string') { 
     //third is the easing function 
    } else if (typeof third == 'function') { 
     //third is the callback function 
    } 
} 
1

检查typeof运算参数的的arguments.length

1

参数的类型可以进行检查。

像:

if (typeof easing == 'function') { 
    complete= easing; 
    easing = 'some default value'; 
} else { 
    // ... 
} 
0

可能:

function test(){}; 
typeof test // 'function'