简体   繁体   English

javascript:传递函数名称与IIFE

[英]javascript: passing a function name vs. IIFE

(Hoping I've got the terminology right...) (希望我的术语正确...)

My code, much simplified: 我的代码,大大简化了:

function foo(parm1, fn){
    // do stuff with parm1, and then...
    window[fn]();
}

function bar(){
    // do the other thing
}

Which is then invoked as: 然后调用为:

foo('some string', 'bar');

I'd like to use a function expression(?), like so: 我想使用一个函数expression(?),像这样:

foo('some string', function(){ // do the other thing });

while retaining the option to pass a function name as in the first example for when what 'bar' has to do is many steps. 同时保留传递函数名称的选项(如第一个示例中所示),其中“ bar”所要做的是许多步骤。 I've tried 我试过了

function foo(parm1, fn){
    // do stuff with parm1, and then...
    if(typeof fn != 'function'){
        window[fn]();
    } else {
        return true;
    }
}

foo('some string', function(){ // but this never fires });

Can I have it both ways? 我可以同时使用吗?

You can. 您可以。 You forgot to call fn if it is a function: 您忘记调用fn如果它是一个函数:

if(typeof fn != 'function'){
    window[fn]();
} else {
    fn(); // fn is (probably) a function so lets call it
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM