1

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?

NotMe
  • 87,343
  • 27
  • 171
  • 245
Tim Bodeit
  • 9,673
  • 3
  • 27
  • 57
  • 3
    What happened when you tried it? Also, closures. – Dave Newton Oct 08 '13 at 22:18
  • +1 to try it, it's even quicker to do that than to ask on this website surely – andygoestohollywood Oct 08 '13 at 22:20
  • In general I would agree, however I'm developing using a framework running on a web service. At the moment, I am not sure if and how I can retrieve error messages from failed JavaScript Code, which is why I wanted to make sure, that the code works before pushing it. – Tim Bodeit Oct 08 '13 at 22:25

1 Answers1

1

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?

Community
  • 1
  • 1
bfavaretto
  • 71,580
  • 16
  • 111
  • 150