Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can ajax callback function see variables from parent function?

function validateHistoryId(input) {
    $.getJSON('request.php', {"action": "historyExists", "history_id" : input.value},
              function(data) {
                  console.log(input.value);
              }
    );
}

i use jQuery ajax call from javascript function. I tried the above code and it works, but I don't know will it cause any problems in the future.

I want to know, can ajax callback function see variables of it's parent function? and is it a bad practice to do so?

like image 922
Sandro Dolidze Avatar asked Oct 19 '12 05:10

Sandro Dolidze


1 Answers

This is the JavaScript functional way to doing things. It's called closure: functions carry variable pointers from their current scope and from any other parent scope. So it's not only good practice, but this is the pattern you should normally follow instead of pushing around parameter objects, etc.

Please notice that the "this" reference is special, it is never closured (as opposed to any other references) and thus always point the global object in anonymous functions.

In fact a developer needs some time to fully employ the power of the closure feature - this is a basic example you just written. In more advanced (and not solely async) scenarios closure helps you to create "fire and forget" behavior, or can provide you with "private" variables that are not accessible from client code (useful for library development). Closure also help you isolate your code so that it will not mess with the global scope.

1) Example: how to create protected variables with closures. You are able to acccess two methods that can access "protectedVariable" but you are not able to access it yourself - so the control is guaranteed.

function protectedScope(initData) {
  var protectedVariable = initData;

  return {
    getter: function()  { return protectedVariable; }
    setter: function(v) { protectedVariable = v; }
  }
}

var methods = protectedScope(10);

console.log(methods.getter());

2) isolation: the following code will not garbage the global scope even with "global" function definitions

var API = (function() {
   var protectedVariable = 0;

   var myNotGlobalFunction() {
      return protectedVariable;
   }

   return myNotGlobalFunction;
})();
like image 185
Peter Aron Zentai Avatar answered Oct 02 '22 02:10

Peter Aron Zentai