在Javascript中将匿名函数作为回调传递 [英] Passing anonymous function as callback in Javascript

查看:88
本文介绍了在Javascript中将匿名函数作为回调传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Javascript中将匿名函数作为自定义回调函数传递?
我有这个代码:

Is there a way to pass anonymous function as a custom callback function in Javascript? I have this code:

function notifyme(msg){
    console.log(msg)
}

notifyme("msg", function(){
    //do some custom redirect logic    
});

我正在尝试上面的代码,它正在执行notifyme功能,但不会进一步使用重定向代码。
我知道我可以传递一个函数名作为回调函数,但是我没有可以通过的特定函数。这就是为什么他们发明了我猜的匿名函数。

I am trying the above code and it's executing notifyme function, but not going further with redirect code. I know I can pass a function name as a callback, but I don't have a specific function that I can pass. This is why they invented the anonymous function I guess.

如果有办法做到这一点真的很好。

It'd be really nice if there was a way to do that.

推荐答案

你的代码模式应该是

function notifyme(msg,callback){
    console.log(msg);
    // Do your stuff here
    if(callback){
      callback();
    }
}

notifyme("msg", function(){
    //do some custom redirect logic    
});

这篇关于在Javascript中将匿名函数作为回调传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆