JavaScript函数,闭包等中的JavaScript函数

时间:2014-01-07 14:41:45

标签: javascript

当我在下面的另一个函数中声明OnSuccess时,浏览器开发人员工具控制台会指示错误,即全局范围内没有名为OnSuccess的函数。据此,我推断在另一个函数中声明如下所示的任何函数仍然作为HTML DOM window对象的函数被提升/固定/处理。

然后,我声明OnError就像在对象初始化器中声明一个成员一样。这也不起作用。

我可以做的一种方法是将OnErrorOnSuccess移到AssignBackupOnServer函数之外,但我希望OnSuccessOnError能够查看AssignBackupOnServer的局部变量,所以我在AssignBackupOnServer函数中声明了它。

如果我希望包含的lambda在其包含/封闭函数的捕获变量上显示闭包,那么正确的方法是什么?

function AssignBackupOnServer(mainGuyUId, backupUId, backupFirstName, backupLastName) {

    var url = '/Foo/SearchForBackup';

    $.ajax(url,
        {
            cache: false,
            async: false,
            type: 'POST',
            data: JSON.stringify(
            { 
              'mainGuyUId': mainGuyUId, 
              'backupUId': backupUId, 
              'backupFirstName': backupFirstName, 
              'backupLastName': backupLastName 
            }),
            dataType: 'json',
            contentType: 'application/json',
            success: AssignBackupOnServer.OnSuccess,
            error: AssignBackupOnServer.OnError
        });

    function OnSuccess(data, textStatus, jqXHR) {
        // I want to use mainGuyUId, backupUId, 
        // backupFirstName, and backupLastName
        // here and therefore, I want this function
        // to exhibit a closure on its containing lambda
        // so I have declared it here
    }

    OnError : function(jqXHR, textStatus, errorThrown) {
    }
}

3 个答案:

答案 0 :(得分:1)

你接近OnSuccess,但引用它时只是略有错误。您不需要AssignBackupOnServer.前缀:

    success: OnSuccess,
    error: OnError
});

function OnSuccess(data, textStatus, jqXHR) {
}

function OnError(jqXHR, textStatus, errorThrown) {
}

答案 1 :(得分:1)

处理此问题的最佳方法是在函数AssignBackupOnServer中为两个函数声明一个标识符,并直接使用这些标识符而不是AssignBackupOnServer。例如

function onSuccess(data, textStatus, jqXHR) { 
  ...
}

function onError(jqXHR, textStatus, errorThrown) { 
  ...
}

$.ajax(url,
        {
         ...
            success: onSuccess,
            error: onError
        });

答案 2 :(得分:0)

对于我所看到的,您愿意重用onSuccessonError函数,但访问外部变量。如果不是这样,理查德的回答就是你所需要的。 如果是的话,我建议采用更具功能性的方法:

function makeSuccess(mainGuyUId, backupUId, backupFirstName, backupLastName){
  return function(data, textStatus, jqXHR){
    // Here you have access to everything
    // and you can use the function elsewhere
  }
}

function makeError(mainGuyUId, backupUId, backupFirstName, backupLastName){
  return function(jqXHR, textStatus, errorThrown){
    // Here you have access to everything
    // and you can use the function elsewhere
  }
}

function AssignBackupOnServer(mainGuyUId, backupUId, backupFirstName, backupLastName) {
  var args = Array.prototype.slice.call(arguments);
  var url = '/Foo/SearchForBackup';

  $.ajax(url,
    {
      //...
      success: makeSuccess.apply(this,args),
      error: makeError.apply(this,args)
    });
}