简体   繁体   English

传递函数名称以作为参数执行

[英]passing function name to execute as parameter

I'm using a $.ajax function that serves two purposes and depending on the context, I want to execute different functions on the call-back. 我正在使用$ .ajax函数,该函数有两个作用,根据上下文,我想在回调上执行不同的函数。

function MyAjaxCall(SomeParameter, CallBackFunctionName) {

  $.ajax({
   ...
   success: function (msg) {

     var TheData = msg.hasOwnProperty("d") ? msg['d'] : msg;
     // here: "execute the function in parameter CallBackFunctionName 
     // AND pass it the parameter TheData
  }
}

How do I write the line where the name of the function is a parameter and I want to pass it TheData as the parameter. 如何在函数名称为参数的行中编写代码,并将其作为参数传递给TheData。

Note, at the moment, I'm writing it like that: 请注意,目前,我正在这样写:

if (CallBackFunctionName === "SomeFunctionName1") {
   SomeFunctionName1(TheData);
} else {
   SomeFunctionName2(TheData);
}

If the function is defined as a global function then use : 如果函数定义为全局函数,则使用:

window[functionName](arguments);

If it isn't then change the way MyAjaxCall is called like so: 如果不是,则更改MyAjaxCall的调用方式,如下所示:

MyAjaxCall.apply(thisArg, [SomeParameter, CallBackFunction]); //thisArg is the value of the this object inside MyAjaxCall().

Then inside MyAjaxCall() do this: 然后在MyAjaxCall()内部执行此操作:

function MyAjaxXall(SomeParam, CallBackFunction){
  var me = this; //the object supplied through thisArg while calling.
  $.ajax({
     success : function(msg)
     {
         //whatever processing you want
         me[CallBackFunction](arguments);
     }

  });
}

Or you could add the object as part of the paramters of MyAjaxCall() : 或者,您可以将对象添加为MyAjaxCall()的参数的一部分:

function MyAjaxCall(SomeParam, obj, CallBackFunction)
{

      $.ajax({
         success : function(msg)
         {
             //whatever processing you want
             obj[CallBackFunction](arguments);
         }

      });
}

When using it for calling a global function use: 在将其用于调用全局函数时,请使用:

MyAjaxCall(SomeParam, window, CallBackFunction);

Assuming that the defined function which name is passed via the variable CallBackFunctionName is global, you could do this: 假设通过变量CallBackFunctionName传递名称的已定义函数是全局的,则可以执行以下操作:

window[CallBackFunctionName](TheData)

You could also just pass the actual function to MyAjaxCall like this: 您也可以像这样将实际函数传递给MyAjaxCall

var MyCallbackFunction = function(data){ console.log(data) }
MyAjaxCall({param1: 'value1'}, MyCallbackFunction)

This way you can just execute the function: 这样,您可以执行以下功能:

function MyAjaxCall(SomeParameter, CallBackFunction) {

  $.ajax({
   ...
   success: function (msg) {

     var TheData = msg.hasOwnProperty("d") ? msg['d'] : msg;
     CallBackFunction(TheData)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM