This might be a stupid question, but I can't seem to leverage google because of all the "Closure 101" links...
In summary, given duplicate code that relies on the closure context, is there a way to de-dup the code into a function call while still having the new function rely only on the closure rather than passing everything it needs via parameters?
A rough code example might look like:
function doWork(){
// initialize variables
// manipulate variables
// ...
$.ajax({
//...
success: function(data){
// DUPLICATE CODE INSTANCE 1 HERE
// RELIES ON VARIABLES IN THE CLOSURE
}
});
// More code
$.ajax({
//...
success: function(data){
// DUPLICATE CODE INSTANCE 2 HERE
// RELIES ON VARIABLES IN THE CLOSURE
}
});
}
As far as I know, if I de-dup the logic in the success blocks into
function onSuccess(...){
// ...
}
Then onSuccess is no longer part of the closure, so would need all the closure variables passed as parameters where the current logic is using the closure to access.
Am I wrong about how closures work? Is there a way to "pass the closure" to the onSuccess function rather than passing individual variables?