扩展存储在变量中的函数

Extend a function stored in a variable

本文关键字:函数 变量 存储 扩展      更新时间:2023-09-26

我有一个大型JavaScript项目,它可以调用几个Ajax web服务。处理web服务调用的代码来自一个共享的外部文件。

为了将web服务与调用代码分离,有一个全局对象引用调用函数,如so

var doRemote ={};
$(document).ready(function(){
doRemote =getRemoteEndpoint('https://someplace.org/MyWebService.aspx');
}

getRemoteEndpoint的简化版本如下:

function getRemoteEndpoint(url) {
    return function(methodName, options) {
        var extension = {
            url: url + '/' + methodName,
            data: {},
            async: true
        };
        var combined = $.extend({}, extension, options);
        combined.data = JSON.stringify(combined.data);
        return $.ajax( combined );
    };
}

我通过以下代码调用web服务调用

doRemote('WebServiceMethodName', 
    {
        success: function(data) {
            alert('Web Service Returned' + data);
        },
        error: function(req, stat, err) {
            alert('Error');
        }
    });

在只在我正在处理的页面中执行getRemoteEndpoint调用之前,我需要先执行一个函数。我不想在30个web服务调用中的每一个调用之前都调用该函数,而是想在该函数中添加一行代码。我已尝试用以下内容替换doRemote分配。

doRemote =function() {
                DoTask();
                return getRemoteEndpoint('https://someplace.org/MyWebService.aspx');
    };

DoTask是我正在处理的程序中的一个命名函数。虽然它不会抛出错误,但Ajax也不会调用work。

我尝试使用JQuery.extend函数,但它也不起作用。

我做错了什么?

您必须实际调用它才能将getRemoteEndpoint结果分配给doRemote:

doRemote = (function() {
    DoTask();
    return getRemoteEndpoint('https://someplace.org/MyWebService.aspx');
})();

更新:

doRemote = (function() {
    var oldDoRemote = getRemoteEndpoint('https://someplace.org/MyWebService.aspx');
    return function(a1, a2) {
      DoTask();
      oldDoRemote(a1, a2);
    }
})();