【问题标题】:Passing function name as a parameter to another function将函数名作为参数传递给另一个函数
【发布时间】:2011-10-14 05:45:19
【问题描述】:

我在 .aspx 页面上从客户端调用 Web 服务,我想在该服务成功时调用一个函数。

函数名将作为参数传递给这个函数,它会动态变化。

我是这样传递的:

function funName parm1, parm2, onSucceedCallFuntion

function onSucceedCallFuntion(result)
//doing something here.    

也许因为它是一个字符串是无法调用“成功”函数的原因

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

【问题讨论】:

    标签: javascript web-services


    【解决方案1】:

    如果你将函数名作为字符串传递,你可以试试这个:

    window[functionName]();
    

    但这假设函数在全局范围内。另一种更好的方法是只传递函数本身:

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

    编辑

    如果您需要将变量传递给函数,您可以将它们与函数一起一起传递。这就是我的意思:

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

    【讨论】:

    • 如果回调有参数怎么办?所以我们需要能够做 doStuff(onSuccess(arg1, arg2));当我尝试这样做时不起作用。