【问题标题】:jQuery methods, order of optional argumentsjQuery 方法,可选参数的顺序
【发布时间】:2012-10-05 13:19:57
【问题描述】:

我只是玩了一下animate() 方法。

.animate( 属性 [, 持续时间] [, 缓动] [, 完成] )

我知道我不必将所有参数传递给 javascript 中的函数。但是我想知道的是jquery是如何计算出function(){ }指的是回调函数,实际上是第4个参数,而不是缓动字符串(也就是第3个)?

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

【问题讨论】:

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

标签: javascript jquery


【解决方案1】:

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

来自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]"

【讨论】:

    【解决方案2】:

    检查参数的typeofarguments.length

    【讨论】:

      【解决方案3】:

      可以检查参数的类型。

      喜欢:

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

      【讨论】:

        【解决方案4】:

        JQuery 查看参数的 type 发现,easing 参数的类型是 string,而 complete 参数的类型是 function

        查看.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
           }
        }
        

        【讨论】:

          【解决方案5】:

          我的猜测是使用 typeof() 来查看参数是否是一个函数,但如果你真的想知道,请查看它们的来源:https://github.com/jquery/jquery

          【讨论】:

            【解决方案6】:

            大概:

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-03-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-06-28
              • 2015-05-17
              • 1970-01-01
              • 2012-06-19
              相关资源
              最近更新 更多