簡體   English   中英

如何將兩個函數的代碼與不同的參數組合在一起?

[英]How can I combine the code of two functions with different arguments?

我有以下兩個功能:

function mvcOnFailure(message) {

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

function ajaxOnFailure(ajaxContext) {

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

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

我在想的是以某種方式有一個函數來完成大部分工作,比如打開對話框,然后讓另外兩個函數從中繼承。

不是繼承 ,但是是的,將公共代碼放在第三個函數中,並從另外兩個函數中調用它。 非常粗略:

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
        ...
    });
}

您可以對兩個回調使用相同的功能。 你所要做的就是檢查你的參數,例如在這種情況下,我會試着看看它是一個對象還是一個字符串(不熟悉MVC,但我認為它將是一個對象)。

然而,這可能是棘手的(甚至是不可能的)並且它可以被認為是錯誤的編碼(基本上傳遞控制變量選擇要執行的代碼),因此保持函數但調用泛型函數來格式化/創建輸出可能是更好的解決方案。

我想message參數是差異。 因此,應該可以將兩個功能合二為一:

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

在ES5中,您不僅可以使用bind來創建具有不同上下文對象的新函數,還可以使用bind來執行currying(http://en.wikipedia.org/wiki/Currying):

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");

現在您有兩個新的displayModal函數,其中第一個參數( title )已經設置。 所以,例如,當你打電話時:

mvcOnFailure("foo");

“foo”將是message參數, title自動為“MVC Error”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM