Please help me understand two thing about callbacks. They are the last JS weirdness left for me that I can’t grasp having strong C# background.
First – why should we send function as parameters. I know that we can, but why. I will try the simplest example I can think of. So according to the JS developers it should be like this:
function simpleCallbackFn (){}
function simpleCallerFn (cb){ cb();}
simpleCallerFn (simpleCallbackFn);
Why not like this:
function simpleCallbackFn (){} // Same as before
function simpleCallerFn (){ simpleCallbackFn ();}
We do not pass a callback, we simply call it from within the caller. It is within perfectly visible scope. Then we just make the initial call.
simpleCallerFn ();
Calling the “callback” function from within the caller function to me should be perfectly fine and achieve the same result.
Second – say I need to use callback with arguments
function simpleCallbackFn (anArgument){}
function simpleCallerFn (cb){
cb(anArgument);
}
We know that this will not work
simpleCallerFn (simpleCallbackFn(anArgument));
According to the JS developers it should be like this:
simpleCallerFn (() => simpleCallbackFn(anArgument));
I am thinking why not:
function simpleCallbackFn (anArgument){}
function simpleCallerFn (anArgument, cb){
cb(anArgument);
}
Then make the initial call like this:
simpleCallerFn (anArgument, simpleCallbackFn);
Please. That Javascript makes me fell like in freak’s circus.
Thank you.