javascript:传递函数名与IIFE
(希望我的术语是正确的…) 我的代码非常简单:javascript:传递函数名与IIFE,javascript,function,iife,Javascript,Function,Iife,(希望我的术语是正确的…) 我的代码非常简单: function foo(parm1, fn){ // do stuff with parm1, and then... window[fn](); } function bar(){ // do the other thing } 然后将其调用为: foo('some string', 'bar'); 我想使用一个函数表达式(?),如下所示: foo('some string', function(){ // do
function foo(parm1, fn){
// do stuff with parm1, and then...
window[fn]();
}
function bar(){
// do the other thing
}
然后将其调用为:
foo('some string', 'bar');
我想使用一个函数表达式(?),如下所示:
foo('some string', function(){ // do the other thing });
当“bar”需要执行许多步骤时,保留第一个示例中传递函数名的选项。我试过了
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 });
两种方式都可以吗?你可以。如果是函数,您忘记调用
fn
:
if(typeof fn != 'function'){
window[fn]();
} else {
fn(); // fn is (probably) a function so lets call it
}
函数foo(parm1,fn){//使用parm1进行填充,然后…if(typeof fn!='function'){window[fn]();}else{fn();}}foo('some string',function(){console.log('function callback…');})
为了防止第二个参数是字符串而不是全局函数时出错,您还可以检查typeof window[fn]=“function”
,我建议使用类型检查(!=
)。