admin管理员组文章数量:1187513
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.
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.
Share Improve this question edited Feb 13, 2017 at 12:03 Lamar asked Feb 13, 2017 at 12:01 LamarLamar 1,8395 gold badges28 silver badges52 bronze badges 2- Possible duplicate of JavaScript Style : optional callbacks – evolutionxbox Commented Feb 13, 2017 at 12:27
- The question is not about optional callback, it's about passing anonymous function call back – Lamar Commented Feb 13, 2017 at 12:45
3 Answers
Reset to default 19Your 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
});
You can call your function simply by invoking it ()
:
function notifyme(msg, myFunc){
console.log(msg);
myFunc();
}
notifyme("msg", () => {
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.
You need to call your callback!
function notifyme(msg, callback){
console.log(msg);
callback();
}
notifyme("msg", function(){
//do some custom redirect logic
});
本文标签: Passing anonymous function as callback in JavascriptStack Overflow
版权声明:本文标题:Passing anonymous function as callback in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738323172a2074594.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论