【问题标题】:jQuery function callingjQuery函数调用
【发布时间】:2011-01-20 02:37:23
【问题描述】:

我有 2 个 jQuery 函数。一个叫另一个(理论上......)。它们是:

$.testFunction = function(arg1){
    alert("testFunction(arg1)");
    $.testFunction(arg1, "");
}

$.testFunction = function(arg1, arg2){
    alert("testFunction(arg1, arg2)");
    alert("arg1: " + arg1 + "\narg2: " + arg2);
}

我有两个函数,因为当我没有传递第二个参数时,我想调用它们的简单版本。 但是当我这样打电话时:

$.testFunction("first param");
alert("Before second call");
$.testFunction("first param", "second param");

它总是调用第二个,并且(在警报窗口中)输入:“testFunction(arg1, arg2)”然后是“arg1: first param arg2: undefined”。为什么会这样工作?当我只传递一个参数时,为什么不调用第一个函数?

【问题讨论】:

    标签: jquery function


    【解决方案1】:

    javascript中没有函数重载,你的第二个函数替​​换了第一个。

    您可以像这样检查arguments 对象来实现类似的效果:

    $.testFunction = function(arg1, arg2){
      if(arguments.length == 1){
       // handle one argument 
      }else if(arguments.length == 2{
       // handle 2 arguments
      }
    }
    

    【讨论】:

      【解决方案2】:

      呃 - 您正在立即覆盖第一个函数。这相当于你正在做的事情:

      x = "foo";
      x = "bar";
      alert(x);  // 'bar' -- "why isn't this foo????!?!"
      

      一个不错的选择是编写一个函数,该函数的行为取决于传递给它的参数数量:

      var testFunction = function(a, b) {
          if (b === undefined) {
              // no second parameter
          }
      };
      

      【讨论】:

        【解决方案3】:

        Javascript 不支持方法重载(至少在传统意义上)是原因。

        第二个函数覆盖第一个函数。

        【讨论】:

          【解决方案4】:

          您正在覆盖该函数。 Javascript 没有重载函数的概念。

          相反,函数采用任意数量的参数,您可以通过特殊的“arguments”属性访问它们。

          $.testFunction = function(arg1, arg2){
              if(arguments.length == 2){
                  alert("arg1: " + arg1 + "\narg2: " + arg2);
              }else{
                  alert("arg1: " + arg1);
              }
          }
          

          【讨论】:

            【解决方案5】:

            您正在重新定义函数并有效地将第一个单参数函数替换为双参数函数。现在你真的只有一个功能。

            您可能想look at this article 这可能有助于超载。

            【讨论】:

              【解决方案6】:
              $.testFunction = function(arg1, arg2){
                  if(arg2 === null || arg2 === undefined){
                      // run the first version
                  }else{
                      // run the second version
                  }
              }
              

              改为尝试 - 这样,您只有一个函数,并且您只需在执行主体之前检查第二个参数是否存在。

              【讨论】:

              • 谢谢大家!我想,这就像在 java 中一样,我可以在其中编写重载方法! ——
              猜你喜欢
              • 2014-11-10
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-10-17
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多