I run into many cases where I find myself needing to do something akin to the following
function main() {
var x = "Something";
foo('do stuff', function bar(stuffResponse) {
var y = x + stuffResponse;
});
}
I.e. a closure where my callback function needs the variable x
I defined previously. This bugs me however as I don't like that my bar
function depends a variable outside of itself, but most of all because I much prefer writing my code like this instead...
function main() {
var x = "Something";
foo('do stuff', bar);
}
function bar(stuffResponse) {
var y = x + stuffResponse;
}
But obviously if I do this bar
has no idea what x
is anymore. Is there a clean way to achieve the latter style whilst retaining the former's functionality?