Passing a function name as a parameter to another function

I am calling web services from the client side on the .aspx page, and I want to call a function for the success of this service.

The name of the function will be passed as a parameter to this function, which will be dynamically changed.

I pass this as follows:

function funName parm1, parm2, onSucceedCallFuntion function onSucceedCallFuntion(result) //doing something here. 

Perhaps because it is a string, so the success function cannot be called

 function funName(parm1, par2, onSucceedFunName) { $.ajax({ url: "../WebServices/ServiceName.asmx/ServiceFunName", data: JSON.stringify({ parm1: parm1, par2: par2 }), // parameter map type: "POST", // data has to be POSTED contentType: "application/json", dataType: "json", success: onSucceedFunName, }); function onSucceedFunName() {} 
+4
source share
1 answer

If you pass the function name as a string, you can try the following:

 window[functionName](); 

But this suggests that the function is in a global area. Another, much better way to do this is to simply pass this function:

 function onSuccess() { alert('Whoopee!'); } function doStuff(callback) { /* do stuff here */ callback(); } doStuff(onSuccess); /* note there are no quotes; should alert "Whoopee!" */ 

Edit

If you need to pass variables to functions, you can simply pass them along with the function. Here is what I mean:

 // example function function greet(name) { alert('Hello, ' + name + '!'); } // pass in the function first, // followed by all of the variables to be passed to it // (0, 1, 2, etc; doesn't matter how many) function doStuff2() { var fn = arguments[0], vars = Array.prototype.slice.call(arguments, 1); return fn.apply(this, vars); } // alerts "Hello, Chris!" doStuff2(greet, 'Chris'); 
+15
source

All Articles