我刚刚玩了一下animate()方法。jQuery方法,可选参数的顺序
.animate(属性[,时间] [,缓和] [,完整])
我知道,我没有给所有的参数传递给在javascript函数。但我想知道的是,如何jquery算出function(){ }
引用回调函数,它实际上是第4个参数,而不是缓动字符串(它是3:rd)?
$('div').animate({ height: '10px' }, 100, function(){ });
我刚刚玩了一下animate()方法。jQuery方法,可选参数的顺序
.animate(属性[,时间] [,缓和] [,完整])
我知道,我没有给所有的参数传递给在javascript函数。但我想知道的是,如何jquery算出function(){ }
引用回调函数,它实际上是第4个参数,而不是缓动字符串(它是3:rd)?
$('div').animate({ height: '10px' }, 100, function(){ });
有简单的测试来检查类型:
从the source code(animate
电话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]"
。
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
}
}
检查typeof运算参数的和的arguments.length。
我的猜测是通过使用typeof(),看是否参数是一个函数,但是如果你真的想知道,看看他们的来源:https://github.com/jquery/jquery
参数的类型可以进行检查。
像:
if (typeof easing == 'function') {
complete= easing;
easing = 'some default value';
} else {
// ...
}
可能:
function test(){};
typeof test // 'function'
这种事情通常是通过检查参数的类型来实现。 – MyStream