Suppose you want to make an async request in JavaScript, but you want to pass some state along to the callback method. Is the following an appropriate use of closures in JavaScript?
function getSomethingAsync(someState, callback) { var req = abc.createRequestObject(someParams); req.invoke(makeCallback(someState, callback)); } function makeCallback(someState, callback) { return function getSomethingCallback(data) { var result = processDataUsingState(data, someState); callback(result); // alternately/optionally pass someState along to result } }
If not, is there a better or more idiomatic way?
I don’t see any immediate problems with this – closures are powerful for numerous reasons, one of which is removing the need to use global variables for state maintenance.
That said, the only thing you need to be wary of with regards to closures is memory leaks that typically occur in IE, but those are usually, IIRC, related to DOM elements and event handlers attached thereto.
Proceed!