Passing anonymous function as callback in Javascript

て烟熏妆下的殇ゞ 提交于 2019-12-07 05:17:41

问题


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    
});

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.


回答1:


Your code pattern should be like

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

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



回答2:


You need to call your callback!

function notifyme(msg, callback){
    console.log(msg);
    callback();
}

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



回答3:


You can call your function simply by invoking it ():

function notifyme(msg, myFunc){
        console.log(msg);
        myFunc();
}
    
notifyme("msg", function(){
        console.log("function called");   
});

myFunc in the above is a variable pointing at your function. By invoking it, () you call the function that the variable (myFunc) points at.

This answer doesn't go into details about the custom redirect logic. Because I don't know what this does.



来源:https://stackoverflow.com/questions/42203554/passing-anonymous-function-as-callback-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!