如何将两个函数的代码与不同的参数组合在一起

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

本文关键字:代码 参数 在一起 组合 函数 两个      更新时间:2023-09-26

我有以下两个函数:

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 创建具有不同上下文对象的新函数,还可以执行 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 错误"。