javascript 将函数名称作为参数传递给另一个函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7763549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:14:00  来源:igfitidea点击:

Passing function name as a parameter to another function

javascriptweb-services

提问by Anu

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

也许因为它是一个字符串,所以无法调用“succeed”函数

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() {}

回答by sdleihssirhc

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 withthe 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');