简体   繁体   中英

Does jQuery accept parameters in any order?

I've noticed when using jQuery.fn.animate() I can pass some or all of the parameters (css for animation, callback function, easing, and duration) in any order to the function.

Looking into the function source code, it starts like this:

function (prop, speed, easing, callback) {
    var empty = jQuery.isEmptyObject(prop),
        optall = jQuery.speed(speed, easing, callback),
.
.
.

And then it starts to actually process the information passed. So, obviously the css properties object has to be first in the chain - otherwise it will break the function (or is it?) . But then look at 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
    };
.
.
.

Obviously this is where the magic's at. But jQuery's approach to cutting down on parentheses and braces makes it difficult for me to breakdown all those conditionals. Can you please simplify the jQuery.speed function? Thanks.

Written in a more comprehensive way, this is what jQuery does:

function (speed, easing, fn) {
    var opt;
    if (speed && typeof speed === "object") {
        opt = jQuery.extend({}, speed);
    }
    else {
        var complete_p,
            duration_p = speed,
            easing_p;

        // Find out what's the "complete" property
        if (fn) complete_p = fn;
        else {
            if (easing) {
                complete_p = easing;
            }
            else {
                if (jQuery.isFunction(speed)) {
                    complete_p = speed;
                }
            }
        }

        // Find out what's the "easing" property
        if (fn) {
            easing_p = easing;
        }
        else {
            if (easing) {
                if (!jQuery.isFunction(easing)) {
                    easing_p = easing;
                }
            }
        }

        opt = {
            complete: complete_p,
            duration: duration_p,
            easing: easing_p
        };
    }
.
.
.

So... yes, it's doing some checks to allow you to change the order. I wouldn't rely on it, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM