Книга: Functional Programming in JavaScript
Назад: The functional programmer's toolkit
Дальше: Array.prototype.map()

Callbacks

If you've never worked with callbacks before, you might find the concept a little puzzling. This is especially true in JavaScript, given the several different ways that JavaScript allows you to declare functions.

A function is used for passing to other functions for them to use. It's a way to pass logic just as you would pass an object:

var myArray = [1,2,3]; function myCallback(x){return x+1}; console.log(myArray.map(myCallback));

To make it simpler for easy tasks, anonymous functions can be used:

console.log(myArray.map(function(x){return x+1}));

They are not only used in functional programming, they are used for many things in JavaScript. Purely for example, here's a function used in an AJAX call made with jQuery:

function myCallback(xhr){   console.log(xhr.status);    return true; } $.ajax(myURI).done(myCallback);

Notice that only the name of the function was used. And because we're not calling the callback and are only passing the name of it, it would be wrong to write this:

$.ajax(myURI).fail(myCallback(xhr)); // or $.ajax(myURI).fail(myCallback());

What would happen if we did call the callback? In that case, the method would try to execute—'undefined' would be printed to the console and it would return . When the call completes, it will have 'true' as the name of the callback function to use, and that will throw an error.

What this also means is that we cannot specify what arguments are passed to the callback functions. If we need different parameters from what the call will pass to it, we can wrap the callback function in an anonymous function:

function myCallback(status){   console.log(status);    return true; } $.ajax(myURI).done(function(xhr){myCallback(xhr.status)});
Назад: The functional programmer's toolkit
Дальше: Array.prototype.map()

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)