如何将动作传递给javascript函数

时间:2013-04-04 17:43:00

标签: javascript

我可以解释我的问题,但可能更容易证明它......

如果您查看http://jsfiddle.net/XxT2B/,您会看到我的问题。我无法弄清楚如何将动作传递给函数。你会明白我的意思。

请注意,根据调用该函数的内容,操作可能会有所不同。行动可能是准时的警报,也可能是下一次的不同。

这是我的代码......

function abc(action)
{
    //Do a bunch of stuff first and then do the action sent to this function
    alert('This function is named "abc"');

    //This is the part I do not know how to do.
    //The action might be an alert or something totally different so I can't just pass text
    //I need to know how to execute the action passed.
    action;
}

abc('alert("I like pizza")');

6 个答案:

答案 0 :(得分:4)

您可以将函数作为参数传递给另一个函数。

function abc(action)
{
    //Do a bunch of stuff first and then do the action sent to this function
    alert('This function is named "abc"');

    action();
}

abc(function(){
    alert("I like pizza");
});

答案 1 :(得分:2)

您可以将函数传递给abc(),但一定要清理

function abc(action)
{
    alert('This function is named "abc"');

    if(typeof(action) == "function") { //sanitize
        action();
    }
}

abc('alert("I like pizza")'); //will execute without a problem
abc(50); //will not run, since 50 is not a function

答案 2 :(得分:1)

您只需要实例化一个函数:

abc(function() { alert("I like pizza"); });

编辑然后调用它,你使用参数的值就像它是一个函数名一样(因为,它就是!):

  action();

答案 3 :(得分:1)

好方法:

将其作为函数传递:

function abc(action)
{
    //Do a bunch of stuff first and then do the action sent to this function
    alert('This function is named "abc"');

    action();
}

abc(function(){alert("I like pizza")});

糟糕的方式(如果你的行为需要是字符串):

function abc(action)
{
    //Do a bunch of stuff first and then do the action sent to this function
    alert('This function is named "abc"');

    eval(action);
}

abc('alert("I like pizza")');

第二种方式不建议,因为eval会导致问题。它可以运行任意代码,可以导致意外的副作用,防止编译器优化,并导致调试困难(因为它可以根据你传递的内容做任何事情)。 More on why eval is bad here.

但它会像你要问的那样运行一个任意字符串作为javascript代码。

答案 4 :(得分:-1)

您可以使用eval方法:

function abc(action)
{
    //Do a bunch of stuff first and then do the action sent to this function
    alert('This function is named "abc"');

    eval(action);
}

abc('alert("I like pizza")');

就是这样。

答案 5 :(得分:-1)

不知道哪个JavaScript版本支持此语法,但是您也可以尝试:

function abc(action) {
if (typeof(action) != 'function')
            return;
    action();

}

abc(() => console.log('A B C'));
相关问题