Edward Sammut Alessi Edward Sammut Alessi - 5 months ago 12
Javascript Question

Closure alternatives

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?

Answer

As stated in the comments, what you're trying to achieve can be done by binding the variable to your callback. That'll give you a copy of the value instead of referencing the original variable:

function main() {
    var x = "Something";

    foo('do stuff', function bar(x, stuffResponse) {
        var y = x + stuffResponse;
    }.bind(null, x));
}

You can also bind this instead of null. However, it doesn't really make sense since you're not using this.