在 JavaScript 中扩展或覆盖函数

Extending or overriding a function in JavaScript

本文关键字:覆盖 函数 扩展 JavaScript      更新时间:2023-09-26

我们在 JavaScript 中有一个关于表单绑定的函数,类似于

var formBind = function( event ) {
    event.preventDefault();
    var form = $(this);
    // some ajax post and validation portion here
    return false;
};

formBind 在许多页面上用作$('form:visible').submit(formBind);

现在我要求在提交之前只在特定页面上应用额外的确认框。如何在对原始代码进行最少更改的情况下添加该功能?

将原始表单嵌套在新函数中绑定

var formBind = function( event ) {
    event.preventDefault();
    var form = $(this);
    // some ajax post and validation portion here
    return false;
};
var additionalFormBind = function( event ) {
    var result = null;
    // do additional work before original formBind
    result = formBind( event );
    // do additional work after original formBind
    return result;
}
$('form:visible').submit(additionalFormBind);

您可以使用 jQuery 的数据参数来传递额外的信息。

$('form:visible').submit({ showConfirm: true }, formBind);

然后签入处理程序:

var formBind = function( event ) { event.preventDefault(); var form = $(this); if(event.data.showConfirm) { // confirmation code goes here. } // some ajax post and validation portion here return false; };

在 JavaScript 中,您可以向函数调用或定义添加任意数量的参数 - 仅使用提供或匹配的参数。 您可以像这样更改函数:

var formBind = function( event, showConfirm ) {
    event.preventDefault();
    var form = $(this);
    if (showConfirm) {
        //logic to display confirmation, followed by a call to the original ajax post if required
    } else {
        // some ajax post and validation portion here
    }
    return false;
};

调用此函数的所有现有位置都不会提供此参数,因此它将未定义,并且if将计算为false并保持原始功能不变。 在新代码中,您可以根据需要truefalse提供它:

$('form:visible').submit(function(e) { return formBind(e, true); });

用包含确认的新函数包装formsubmit函数。

$('form:visible').submit(confirmAndSubmit);
var confirmAndSubmit = function( event ) {
    event.preventDefault();
    return (window.confirm("Are You Sure?"))?formsubmit(event):false;
};