Answer the question
In order to leave comments, you need to log in
How to properly call a callback function?
Good evening everyone!
I have a theoretical question, I can not understand the syntax and logic of using callback functions. Everything that I googled - talks about the same examples and does not give me an understanding of the following points:
var func = function(callback){
var name = "Max";
callback(name);
};
func(function(n){
console.log("Hi " + n);
});
Answer the question
In order to leave comments, you need to log in
Functions Have Parameters
When you call a callback function, it's the same as calling fn with parameters like this.
Your case
function fn (a, b, c) { alert(a, b, c) }
function foo (callback) {
var a = 1, b = 2, c = 3
callback(1, 2, 3) // равносильно fn (1, 2, 3)
}
foo(fn)
Hm... A function can be written into a variable, into anything. Imagine an example:
function a(name) {
alert(name);
}
a("Vanya");
function a(name, callback) {
alert(name);
callback(name);
}
a("Vanya", function(name) { console.log(name); });
Here, creatively rethought, everything seems to be clear and everything works:
function fuck(girl, boy, callback){
var hookUp;
if(girl >=18 && boy >=18){
hookUp = true;
}else hookUp = false;
callback(hookUp);
}
fuck(19,30, function(hookUp){
if(hookUp){
console.log("You're welcome!");
}else console.log("No way!!!");
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question