2012-05-06 46 views
1

我有以下兩個功能:如何將兩個函數的代碼與不同的參數結合起來?

function mvcOnFailure(message) { 

    $.modal({ 
     title: "MVC Error", 
     closeButton: true, 
     content: message, 
     ... 
    }); 
} 

function ajaxOnFailure(ajaxContext) { 

    $.modal({ 
     title: "Ajax Error", 
     closeButton: true, 
     content: ajaxContext.responseText, 
     ... 
    }); 
} 

他們都做同樣的事情(某些行省略),但是採取不同的參數。有什麼方法可以組合這些功能嗎?我在想的是以某種方式有一個功能來完成大部分的工作,比如打開對話框,然後再從其中繼承另外兩個功能。

+5

這不是C#。 – BoltClock

+0

爲什麼這個標記爲C#? – ChrisWue

+0

現在已經被海報改變了。對不起,錯了標籤。 –

回答

3

我在想的是以某種方式有一個功能來完成大部分的工作,比如打開對話框,然後有兩個其他的繼承。

繼承,惟命是從,把公共代碼在第三功能和調用其他兩個它。非常大致:

function mvcOnFailure(message) { 

    doTheCommonStuff("MVC Error", message /*, other, stuff */); 
} 

function ajaxOnFailure(ajaxContext) { 

    doTheCommonStuff("Ajax Error", ajaxContext.responseText /*, other, stuff */); 
} 

function doTheCommonStuff(title, content /*, other, stuff */) { 
    $.modal({ 
     title: title, 
     closeButton: true, 
     content: content 
     ... 
    }); 
} 
0

您可以對兩個回調使用相同的函數。您只需檢查您的參數,例如在這種情況下,我會試着看看它是一個對象還是一個字符串(不熟悉MVC,但我認爲它會是一個對象)。但是這可能會很棘手(甚至不可能),並且它可能被認爲是不好的編碼(本質上是傳遞一個控制變量來選擇要執行的代碼),所以保留函數但調用一個通用函數來格式化/創建輸出是更好的解決方案。

0

我想message參數是不同的。因此,它應該是可能的兩種功能結合在一個:

function mvcOrAjaxOnFailure(message) { 
    $.modal({ 
     title: message.responseText ? "Ajax (XHR) Error" : "MVC Error", 
     closeButton: true, 
     content: message.responseText || message, 
     ... 
    }); 
} 
0

在ES5你可以使用bind不僅要創造一個不同的上下文對象的新功能外,還進行柯里(HTTP:// EN .wikipedia.org /維基/柯里):

function displayModal(title, message) { 
    $.modal({ 
     title: title, 
     closeButton: true, 
     content: message, 
     ... 
    }); 
} 

var mvcOnFailure = displayModal.bind(undefined, "MVC Error"); 
var ajaxOnFailure = displayModal.bind(undefined, "Ajax Error"); 

現在你有其中第一個參數(title)已經設置了兩個新的displayModal功能。所以,舉例來說,當你撥打:

mvcOnFailure("foo"); 

「FOO」 將是message參數,title自動 「MVC錯誤」。

相關問題