Question

When using blocks in Objective C, it is possible to use all of the variables, that were accessible inside the function where the block was defined.

Does the same apply to JavaScript functions defined as a variable?

For example, will the successFunction work properly, when called from inside of someOtherFunction, since it was declared inside of beforeSaveFunction?

var beforeSaveFunction = function(request, response) {

    var successFunction = function(code) {
        request.object.set("sessionAuthCode",code);
        response.success();
    }

    someOtherFunction(successFunction);
}

Or will I have to do this and pass along the variables inside someOtherFunction:

var beforeSaveFunction = function(request, response) {

    var successFunction = function(code, request, response) {
        request.object.set("sessionAuthCode",code);
        response.success();
    }

    someOtherFunction(successFunction, request, response);
}

If Option 1 doesn't work, is there an easier alternative than Option 2?

Was it helpful?

Solution

Yes, that's how JavaScript closures work. As long as a variable is in scope where the function is defined, it's in scope within the function when it's called.

See: How do JavaScript closures work?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top