[英]Passing function name as a parameter to another function
I am calling a web services from client side on .aspx page, and I want to call a function on the success of this service. 我在.aspx页面上从客户端调用Web服务,我想调用一个关于此服务成功的函数。
The name of function will be passed as a parameter to this function, which will dynamically change. 函数名称将作为参数传递给此函数,该函数将动态更改。
I am passing it like this: 我这样传递:
function funName parm1, parm2, onSucceedCallFuntion
function onSucceedCallFuntion(result)
//doing something here.
Perhaps because it's a string is why the "succeed" function could not 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() {}
If you're passing the name of the function as a string, you could try this: 如果您将函数的名称作为字符串传递,您可以尝试这样做:
window[functionName]();
But that assumes the function is in the global scope. 但这假设功能在全球范围内。 Another, much better way to do it would be to just pass the function itself:
另一种更好的方法是只传递函数本身:
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 the function, you can just pass them in along with the function. 如果需要将变量传递给函数,可以将它们与函数一起传递。 Here's 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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.