Event Listener and AJAX asynchronous function variable scope
I got a question, probably very simple, but whatever. When registering an event listener inside an asynchronous function, I would believe that all values within that function would be non-existing when the function has run it's course.
However, an event listener, as displayed below in the code can still access the variable values
, how is that? Is the variable saved within the event listener somehow?
$.ajax({
type: "GET",
cache: false,
url: "/whatever",
success: function(data) {
var values = ["Some Values", "Inside this Object"];
$("#id :checkbox").click(function() {
var allValues = [];
$('#id3 :checked').each(function() {
allValues.push($(this).val());
});
$("#id2").val(allValues);
callMe.init(values,allValues);
});
开发者_如何转开发 }
});
This is because of closures. A function "closes over" all variables in its lexical scope, which is to say that it retains access to them once the function in which it was defined has returned.
In your specific example, values
is in scope when the function given to click
is defined, so it will remain accessible even once success
completes.
You'll find a lot more information here:
- How do JavaScript closures work?
The JQuery $ sign is in the global scope. Anything can reference it. You are reaching the form checkbox values through $.
精彩评论