I have been writing javascript for quite a long time, but so far some features of the language are not clear to me. There is an example code. The body of the function is passed to it. Please explain with the example of your code how to make it so that you can pass the body of the function to the argument and how you can call it later. I cannot understand this moment for quite a long time. Thank!

var body = document.getElementsByTagName('body')[0]; body.addEventListener('click', function() { alert('body'); }); 

    1 answer 1

    Passing a function as an argument to another function:

     function someProcedure(callback) { var blaBlaBla = 5; callback(blaBlaBla * 10); }; function iAmCallback(someNumber) { alert("someNumber is: " + someNumber); }; someProcedure(iAmCallback); 

    We call our procedure someProcedure with an argument to a function that will be called as a callback after certain manipulations.

    This is just a basic example, something like this is most often used in this approach (count something in one function, and call the argument function with the results of calculations)

    Just in case, I will clarify: the function-argument is called exactly the same as a regular function, you simply refer to it as a variable

    • I did it based on your example and I did it. Thanks for the detailed story! function func_main (callback) {callback (); } func_main (function () {alert (100);}); - Anton
    • @ Anton If my answer is correct - please accept it as appropriate by clicking on the check mark under the arrows - Klimenkomud