将函数作为 Javascript 中可能尚不存在的参数传递

Pass a function as a parameter that may not exist yet in Javascript

本文关键字:不存在 参数传递 函数 Javascript      更新时间:2023-09-26

是否可以传递尚不存在的回调函数? 我的目标是拥有一个通用函数,它将等待另一个回调函数存在,当它确实存在时,它应该执行它。 这就是我目前所拥有的,但我无法弄清楚如何将尚不存在的函数作为函数传递。

function RunTemplateFunction(callback, userInfo) {
if ($.isFunction(callback)) {
    callback(userInfo);
} else {
    var myInterval = setInterval(function () {
        if ($.isFunction(callback)) {
            clearInterval(myInterval);
            callback(userInfo);
        }
    }, 200);
}
}

我像这样运行函数:

RunTemplateFunction(MyFunctionToRun, GetUserInfo());

由于显而易见的原因,我得到 MyFunctionToRun 未定义,我还尝试了将函数作为字符串传递然后使用 eval() 将字符串转换为函数的解决方法。 但这会引发同样的错误。 我也想到使用new函数(),但这实际上创建了一个新函数。

任何帮助,不胜感激。 谢谢。

如果你通过undefined调用RunTemplateFunction,我们没有办法看到回调是否被定义,因为我们没有引用任何东西。

如果您可以修改声明以接受以下object,我们可以实现我们想要的

function RunTemplateFunction(options, userInfo) {
    if ($.isFunction(options.callback)) {
        console.log('called1',userInfo);
        options.callback(userInfo);
    } else {
        var myInterval = setInterval(function () {
            if ($.isFunction(options.callback)) {
                console.log('Called dynamically!!');
                clearInterval(myInterval);
                options.callback(userInfo);
            }
        }, 200);
    }
}
var options = {}
RunTemplateFunction(options,{user:122});
options.callback = function(){
 console.log("I'm called!!");
}

这将打印

Called dynamically!!
I'm called!!

编辑:

我们也可以在没有setInterval的情况下按以下方式调用callback函数,它看起来会有所不同options.callback但变量被template.callMe函数及其瞬时函数替换。

function TemplateRunner(userInfo){
  this.callMe = function(cb){
    this.templateFunction(cb);
  }
  this.templateFunction = function(callback){
   callback(userInfo);
  }
}
var template = new TemplateRunner({user:100})
template.callMe(function(user){
  console.log('call me1',user);
});
template.callMe(function(user){
  console.log('call me2',user);
})

这将打印

call me1 {user: 100}
call me2 {user: 100}