variable scope in AJAX calls

2019-07-18 08:51发布

问题:

one question I always ask myself is how is it possible that javascript has still a reference in a callback function of a AJAX request when the variable was declared in the function which isssues the AJAX call. Here an example

var loadMask = {name:"test"};

form.submit({
  url: 'request.php',
  timeout : 180000,
  success: function(the_form, action_object)
  {    
    console.log(loadMask);
  }
});

despite the fact that loadMask was declared outside of the success function it is still visible (and defined) inside.

How is this possible?

回答1:

This is possible using something called closures. There are many resources for this:

Here's a few from a google:

http://www.webreference.com/programming/javascript/rg36/

http://jibbering.com/faq/notes/closures/