Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery methods, order of optional arguments

I just played around a bit with the animate() method.

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

I know that I dont have to pass all the arguments to a function in javascript. But what I would like to know is how jquery figures out that function(){ } refers to the callback function, which is actually the 4:th parameter, instead of the easing string (which is the 3:rd)?

$('div').animate({ height: '10px' }, 100, function(){ });
like image 952
Johan Avatar asked Feb 18 '26 21:02

Johan


2 Answers

There are simply tests to check the type :

From the source code (animate calls 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();
});

So basically it checks that Object.prototype.toString.call(fn) is "[object Function]".

like image 181
Denys Séguret Avatar answered Feb 21 '26 09:02

Denys Séguret


Check the typeof of argument and arguments.length.

like image 22
JNo Avatar answered Feb 21 '26 09:02

JNo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!