且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-09 23:13:46

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

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