2010-02-23 55 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這可能有助於超載。