javascript:传递函数名与 IIFE
javascript: passing a function name vs. 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 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
}
(希望我的术语正确...)
我的代码,大大简化了:
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
}