2010-02-23 93 views
1

我有2个jQuery函数。一个叫另一个(理论上......)。它们是: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:第一个参数ARG2:未定义 ”。为什么这样工作?为什么当我只传递一个参数时不会调用第一个函数?

回答

1
$.testFunction = function(arg1, arg2){ 
    if(arg2 === null || arg2 === undefined){ 
     // run the first version 
    }else{ 
     // run the second version 
    } 
} 

试试这个 - 而这样,你只有一个函数,你只需在执行正文前检查第二个参数的存在。

+0

谢谢大家!我想,这是像在Java中,我可以写重载的方法! - – user196776 2010-02-23 15:18:34

1

在JavaScript中没有函数重载,您的第二个函数会替换第一个函数。

你可以实现类似的检查arguments对象是这样的:

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

+1给大家! (因为你们都在同一时间回答) – 2010-02-23 14:49:24

1

呃 - 你立即覆盖第一个功能。下面是你在做什么等价的:

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

一个很好的选择将取决于传递给它的参数的个数来写这表现不同的单一功能:

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

的Javascript没有按” t支持方法重载(至少在传统意义上)是原因。

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

1

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

取而代之,函数接受任意数量的参数,您可以通过特殊的“arguments”属性访问它们。

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

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

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