将函数名称作为参数传递给另一个函数 [英] Passing function name as a parameter to another function

查看:113
本文介绍了将函数名称作为参数传递给另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

函数名称将作为参数传递给此函数,该函数将动态更改。

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

我这样传递:

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!" */

编辑

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

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

这篇关于将函数名称作为参数传递给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆