Javascript 将可选函数作为参数传递给另一个函数

Javascript 将可选函数作为参数传递给另一个函数,javascript,jquery,Javascript,Jquery,如何调用函数的选项: myAjax("http://ajaxurl.com", { prop: val }, function(resp) { alert(resp); }); if (typeof successFunc == 'function') { successFunc(response); } 或 或 或 我如何在myAjax函数定义中处理这个问题?像这样的东西 function myAjax(url, jsonData, successFunc) { $.ajax(

如何调用函数的选项:

myAjax("http://ajaxurl.com", { prop: val }, function(resp) { alert(resp); });
if (typeof successFunc == 'function') {
    successFunc(response);
}

我如何在myAjax函数定义中处理这个问题?像这样的东西

function myAjax(url, jsonData, successFunc) {
  $.ajax({
    ... all the necessary ajax stuff that normally goes here
    , success: function(response) {
      // custom myAjax success handling goes here. this must happen before optionally-passed-in successFunc gets executed

      // what goes here? this?
      if (typeof successFunc != 'undefined' && successFunc != null) {
        successFunc(response);
      }
    }
  });
}
我尝试了上面的方法,但是,它没有调用success函数。是否需要检查successFunc是否为函数


谢谢

不要针对未知类型进行测试,而是验证该函数确实是一个函数:

myAjax("http://ajaxurl.com", { prop: val }, function(resp) { alert(resp); });
if (typeof successFunc == 'function') {
    successFunc(response);
}
但是,当前代码不会阻止运行
successFunc
。确保成功处理AJAX请求(无错误,无跨域限制)


由于您的代码没有达到调用
successFunc
,因此在
if(typeof…

测试typeof successFunc是否为“function”之前可能会生成错误:

function myAjax(url, jsonData, successFunc) {
  $.ajax({
    ... all the necessary ajax stuff that normally goes here
    , success: function(response) {
      // custom myAjax success handling goes here. this must happen before optionally-passed-in successFunc gets executed

      // what goes here? this?
      if (typeof successFunc === 'function') {
        successFunc(response);
      }
    }
  });
}

typeof successFunc=='function'
代替或补充?谢谢!
function myAjax(url, jsonData, successFunc) {
  $.ajax({
    ... all the necessary ajax stuff that normally goes here
    , success: function(response) {
      // custom myAjax success handling goes here. this must happen before optionally-passed-in successFunc gets executed

      // what goes here? this?
      if (typeof successFunc === 'function') {
        successFunc(response);
      }
    }
  });
}